2

我对“IFS=$'\n' 有疑问。

old_IFS=$IFS
file="Good morning
Good morning
Good morning
Good morning
Good morning"

IFS=$'\n'
for line in $file
    do
       echo $line
done
IFS=$old_IFS

当我执行脚本时:

Good mor
i
g
Good mor
i
g
Good mor
i
g
Good mor
i
g
Good mor
i
g

“n”被删除。我想逐行查看文件

4

2 回答 2

2

迭代多行数据(无论您的 shell 是否支持$'...')的正确方法是使用重复while调用的循环read

while read -r; do
    echo "$REPLY"
done <<EOF
$file
EOF
于 2014-05-27T15:28:43.563 回答
1

正如其他人指出的那样,我认为您使用的 shell 不支持$'...'语法。

如果您的系统使用 Dash as sh,您应该能够IFS通过将其分配给空或未分配的变量来分配新行。例如,n=""; IFS=$n将允许您按新行拆分。这是一个 hack,只有在空变量被解释为解释器的新行时才有效。

您还可以使用<<<word.

file="Good morning
Good morning
Good morning
Good morning
Good morning"

while read line; do
    echo $line
done <<<"$file"

否则,您可以逐行读取文件。

while read -r line; do 
    echo "$line"
done < file
于 2014-05-26T15:32:46.353 回答