在 bash 中,“for;do echo;done”在空格处分割线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8694746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:14:13  来源:igfitidea点击:

in bash, "for;do echo;done" splits lines at spaces

macosbashecho

提问by atheaos

In bash on Mac OSX, I have a file (test case) that contains the lines

在 Mac OSX 上的 bash 中,我有一个包含以下行的文件(测试用例)

x xx xxx
xxx xx x

But when I execute the command

但是当我执行命令时

for i in `cat r.txt`; do echo "$i"; done

the result is not

结果不是

x xx xxx
xxx xx x

as I want but rather

如我所愿,而是

x
xx
xxx
xxx
xx
x

How do I make echo give me 'x xx xxx'?

我如何让 echo 给我 'x xx xxx'?

回答by Oliver Charlesworth

By default, a Bash for loop splits on all whitespace. You can override that by setting the IFSvariable:

默认情况下,Bash for 循环在所有空白处拆分。您可以通过设置IFS变量来覆盖它:

IFS=$'\n'
for i in `cat r.txt`; do echo "$i"; done
unset IFS

回答by fge

Either setting IFSas suggested or use while:

IFS按照建议设置或使用while

while read theline; do echo "$theline"; done <thefile

回答by Arenielle

IFS="\n"
for i in `cat r.txt`; do echo "$i"; done
unset IFS