我有一个这样的文本文件;
192.168.1.1 apple orange
192.168.1.2 banana
192.168.1.3 kiwi melon cherry
我想逐行循环遍历这个文件,并将每行中的项赋值给多个参数。例如,当我像这样运行它时;
for loop from textile above;
echo "Args: $1 $2 $3 $4"
done
它应该给出如下输出;
Args: 192.168.1.1 apple orange
Args: 192.168.1.2 banana
Args: 192.168.1.3 kiwi melon cherry
另外,正如您所看到的,每行在固定的IP之后可能包含1到3个参数。所以IP总是在那里,它是$1
,其余的可以在$2
和$4
之间变化。
我该怎么做?我能够通过使用mapfile
读取文件,但无法从中获得参数。
mapfile
将其标准输入的行分配给索引数组的项,而您希望将每行的字段分配给数组。这不是一回事。如果您的输入文件与您所显示的一样简单,则可以使用以下内容:
$ while read -r -a args; do
set -- "${args[@]}"
echo "$# arguments: $@"
done < textfile.txt
3 arguments: 192.168.1.1 apple orange
2 arguments: 192.168.1.2 banana
4 arguments: 192.168.1.3 kiwi melon cherry
但是如果你的输入更复杂(例如,参数中有空格),这当然不会像你期望的那样工作。
编辑:看到Paul的回答后把set "${args[@]}"
改成了set -- "${args[@]}"
。
完全基于OP的期望输出:
$ sed 's/^/Args: /' textfile.txt
Args: 192.168.1.1 apple orange
Args: 192.168.1.2 banana
Args: 192.168.1.3 kiwi melon cherry
假设OP的真正需求是对值做一些事情(而不是回显到stdout):
while read -r ip fruit1 fruit2 fruit3
do
echo "Args: ${ip} ${fruit1} ${fruit2} ${fruit3}" # yeah, extra spaces when fruit? is empty but visually not noticeable
# or do other stuff ...
done < textfile.txt