我有嵌套循环的麻烦。代码如下所示:
while IFS='' read -r line || [[ -n "$line" ]]; do
num=0
for i in $line; do
eval a_${num}="\"$(echo $i)\""
echo $a_0
((num=num+1))
done
done < file
文件中有许多行。每一行由16个空格分隔值组成: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
当我读取文件中的每一行时,应该将i的第一次出现设置为变量a_。
因此,当我回显这个值时,如果文件中有两个相同的行,那么它应该读取:
01
01
然而,这就是所发生的事情:
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
01
它不是两次回显,而是迭代行中值的两倍-- 16+16时间。我在这里做错什么了?
发布于 2017-11-06 00:53:30
过了一段时间,这段代码(几乎)解决了我的问题:
file=`cat files.txt`
# read the lines in the file and store every line in variable as "line"
while read -r line; do
# declare an array variable from every space separated value in "line"
declare -a arr=`echo $line`
# set counter to zero
num=0
# now loop through the above array
for i in ${arr[*]}; do
# set a variable as "a_$num" that equals the current value in array
eval a_${num}="'\"$(echo $i)\"'"
# incremenate "num" by 1
((num=num+1))
done
# echo the first value in current line
echo $a_0
done <<< $file
现在的结果应该是:
01
01
……但出于某种原因,它只得到了一次回应,尽管有两句话:
01
不过我还是可以用剧本的。如果有人能解决最后一点,那就太好了!
https://stackoverflow.com/questions/47094298
复制相似问题