如何循环文件中的多行数组并将每一行分配给多个参数?
How to loop through multiline array from a file and assign each line to multiple arguments?
我有一个这样的文本文件;
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: "
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 始终存在,它是 </code>,其余的可以在 <code>
和 </code> 之间变化。</p>
<p>我该怎么做?我能够使用 <code>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 的真正要求是对值做一些事情(除了回显到标准输出):
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
我有一个这样的文本文件;
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: "
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 始终存在,它是 </code>,其余的可以在 <code>
和 </code> 之间变化。</p>
<p>我该怎么做?我能够使用 <code>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 的真正要求是对值做一些事情(除了回显到标准输出):
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