bash 脚本,读取文件的每一行并存储到不同的变量(但未找到命令的消息)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11678054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:52:55  来源:igfitidea点击:

bash script that reads each line of a file and stores to different variables (but got command not found message)

bashloopssedcommandexecute

提问by pohe

Thanks for your help in advance. I'm writing a simple bash script, which just read each line of a file, and then store each line into a different variable. For example, I'd like the script to perform the following commands:

提前感谢您的帮助。我正在编写一个简单的 bash 脚本,它只是读取文件的每一行,然后将每一行存储到不同的变量中。例如,我希望脚本执行以下命令:

d1=AER
d2=BHR
d3=CEF
...

Therefore, I have a text file that has 10 lines, and each line is the content of the variables I'd like to store (e.g., AER), and I have the following test.sh script:

因此,我有一个有 10 行的文本文件,每一行都是我想要存储的变量的内容(例如,AER),我有以下 test.sh 脚本:

#!/bin/bash
for i in {1..10..1}
do
    $(d$i=$(sed -n ${i}p $HOME/textfile.txt))
done

However,when executing the script, it gave me

但是,在执行脚本时,它给了我

./test.sh: line 4: d1=AER: command not found
./test.sh: line 4: d2=BHR: command not found
./test.sh: line 4: d3=CEF: command not found
...

,instead of storing the characters into corresponding variables. Could somebody please identify where I did it wrong? Thank you so much!

, 而不是将字符存储到相应的变量中。有人可以指出我哪里做错了吗?非常感谢!

回答by Jake

The problem with your script is that if you need to interpolate a variable on the first line, bash thinks its the name of a program and tries to execute it. You can eval it, to make the variable:

您的脚本的问题在于,如果您需要在第一行插入一个变量,bash 会认为它是程序的名称并尝试执行它。你可以评估它,使变量:

eval "d$i=$(sed ...)"

but its much simpler to use the read bash built-in, since it takes line input to a specified variable. Here's one way to do it:

但是使用内置的 read bash 简单得多,因为它需要对指定变量的行输入。这是一种方法:

for ((i=1;; i++)); do
    read "d$i" || break;
done < textfile.txt
echo "$d1"
echo "$d2"

回答by Ignacio Vazquez-Abrams

Use an array, but the right way.

使用数组,但方法正确。

read -a d -d '\n' < textfile.txt
echo "${d[1]}"

回答by twalberg

As an alternative to the array solution, you can use eval.

作为阵列解决方案的替代方案,您可以使用eval.

((lnum=1))
exec 3< ${filetoread}
while read -u3 line
do
  eval `echo d${lnum}=\"${line}\"`
  ((lnum=1+${lnum}))
done
exec 3<&-