如何在变量中或从命令输出中正确地遍历bash中的行?只需将IFS变量设置为新行即可用于命令的输出,但不适用于处理包含新行的变量。
例如
#!/bin/bash
list="One\ntwo\nthree\nfour"
#Print the list with echo
echo -e "echo: \n$list"
#Set the field separator to new line
IFS=$'\n'
#Try to iterate over each line
echo "For loop:"
for item in $list
do
echo "Item: $item"
done
#Output the variable to a file
echo -e $list > list.txt
#Try to iterate over each line from the cat command
echo "For loop over command output:"
for item in `cat list.txt`
do
echo "Item: $item"
done
这给出了输出:
echo:
One
two
three
four
For loop:
Item: One\ntwo\nthree\nfour
For loop over command output:
Item: One
Item: two
Item: three
Item: four
如您所见,在cat
命令中回显变量或迭代将正确打印每一行。但是,第一个for循环将所有项目打印在一行上。有任何想法吗?
只是对所有答案的评论:我必须做$(echo“ $ line” | sed -e's / ^ [[:space:]] * //'),以修剪换行符。
—
servermanfail