如何从文件中填充变量?

时间:2021-11-09 15:57:55

How can I fill the variables from file?

如何从文件中填充变量?

In /root/file I have 4 lines (number and text)

在/ root / file我有4行(数字和文本)

478
144
text
0

How can I set the values of four variables, one value from each line of the file?

如何设置四个变量的值,文件的每一行中的一个值?

The desired result:

期望的结果:

ABC="478"
DEF="144"
GHI="text"
JKL="0"

1 个解决方案

#1


Say the file is called file.txt. Just read each line into the desired variable, one at a time, using a compound command.

假设该文件名为file.txt。只需使用复合命令将每一行读入所需变量,一次一个。

{ IFS= read -r ABC; IFS= read -r DEF; IFS= read -r GHI; IFS= read -r JKL; } < file.txt

If you know that file.txt is "simple", that is, you don't care about leading or trailing whitespace on the lines or backslash-escaped line continuations, you can drop the IFS= and -r clutter and just use

如果你知道file.txt是“简单的”,也就是说,你不关心行上的空格或尾随空格或反斜杠转义的行继续,你可以删除IFS =和-r杂乱并只使用

{ read ABC; read DEF; read GHI; read JKL; } < file.txt

We use the compound command { ... } to share the input from file.txt among all the reads; without it, using something like

我们使用复合命令{...}来共享所有读取中file.txt的输入;没有它,使用类似的东西

read ABC < file.txt
read DEF < file.txt
read GHI < file.txt
read JKL < file.txt

each read would read from the beginning of the file, resulting in the first line of the file being assigned four times.

每次读取都将从文件的开头读取,导致文件的第一行被分配四次。

#1


Say the file is called file.txt. Just read each line into the desired variable, one at a time, using a compound command.

假设该文件名为file.txt。只需使用复合命令将每一行读入所需变量,一次一个。

{ IFS= read -r ABC; IFS= read -r DEF; IFS= read -r GHI; IFS= read -r JKL; } < file.txt

If you know that file.txt is "simple", that is, you don't care about leading or trailing whitespace on the lines or backslash-escaped line continuations, you can drop the IFS= and -r clutter and just use

如果你知道file.txt是“简单的”,也就是说,你不关心行上的空格或尾随空格或反斜杠转义的行继续,你可以删除IFS =和-r杂乱并只使用

{ read ABC; read DEF; read GHI; read JKL; } < file.txt

We use the compound command { ... } to share the input from file.txt among all the reads; without it, using something like

我们使用复合命令{...}来共享所有读取中file.txt的输入;没有它,使用类似的东西

read ABC < file.txt
read DEF < file.txt
read GHI < file.txt
read JKL < file.txt

each read would read from the beginning of the file, resulting in the first line of the file being assigned four times.

每次读取都将从文件的开头读取,导致文件的第一行被分配四次。