英文:
Bash read file assign each line to variables
问题
这是我的文件
1 2 3
4 5 6
7 8 9
以下是我的代码
i=0;
while read line;do
arry_$i="${line[@]}";
i=$(($i+1));
done < file.txt
IFS=' '; eval "arr_00=($arr_0)"
IFS=' '; eval "arr_11=($arr_1)"
IFS=' '; eval "arr_22=($arr_2)"
以下是输出
arry_0=1 2 3: 未找到命令
arry_1=4 5 6: 未找到命令
arry_2=7 8 9: 未找到命令
当我尝试将文件的每一行分配给变量时,出现了“未找到命令”的错误提示。
感谢您的建议。
英文:
This is my file
1 2 3
4 5 6
7 8 9
Following is my code
i=0;
while read line;do
arry_$i="${line[@]}";
i=$(($i+1));
done < file.txt
IFS=' ';eval "arr_00=($arr_0)"
IFS=' ';eval "arr_11=($arr_1)"
IFS=' ';eval "arr_22=($arr_2)"
Following is the output
arry_0=1 2 3: command not found
arry_1=4 5 6: command not found
arry_2=7 8 9: command not found
When I try to assign file each line to variable noticed an "command not found"
Thank you for suggestions
答案1
得分: 1
只是处理错误消息:
当您执行:
arry_$i="${line[@]}";
shell 不会将其识别为变量赋值,因为它不匹配形式 name=[value]
,因为 arry_$i
不是一个有效的名称形式。
在此之后,它执行各种扩展、分词、去引号等操作。在第一个循环迭代中,这会导致一个词 arry_0=1 2 3
。
这个词被视为要运行的命令。这就是您的错误消息。
尽管强烈建议不要执行以下操作,但您可以通过在尝试赋值之前生成变量名称来修复问题:
while read line; do
declare -n var=arry_$i
var=$line;
((i++))
done < file.txt
请注意,由于 line
是一个简单的变量而不是数组,${line[@]}
== ${line[0]}
== $line
。
我不确定您的 exec
的目的是什么。
对于所示的示例数据,直接执行 arry_00=($arry_0)
等将是可以的。
英文:
Just addressing the error message:
When you do:
arry_$i="${line[@]}";
the shell does not recognise this as a variable assignment as it does not match the form name=[value]
because arry_$i
is not a valid form for a name.
After this it performs the various expansions, word-splitting, quote-removal, etc. On the first loop iteration, this results in a word arry_0=1 2 3
.
This word is treated as a command to run. This gives your error message.
While strongly advising that you do not do the following, you could fix the problem by making the variable name generation happen before you attempt to assign to it:
while read line; do
declare -n var=arry_$i
var=$line;
((i++))
done < file.txt
Note that since line
is a simple variable and not an array, ${line[@]}
== ${line[0]}
== $line
.
I'm not sure what the purpose of your exec
is.
For the sample data shown, it would be fine to directly execute: arry_00=($arry_0)
, etc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论