bash 带新线的猫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2460377/
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-09 19:03:59  来源:igfitidea点击:

Cat with new line

bash

提问by muruga

My input file content is

我的输入文件内容是

welcome

welcome1

welcome2

欢迎

欢迎1

欢迎2

My script is

我的脚本是

for groupline in `cat file`
do
        echo $groupline;
done

I got the following output.

我得到了以下输出。

welcome
welcome1
welcome2 

Why it is not print the empty line. I want the reason.

为什么不打印空行。我要原因

回答by ghostdog74

you need to set IFSto newline \n

你需要设置IFS为换行符\n

IFS=$"\n"
for groupline in $(cat file)
do
        echo "$groupline";
done

Or put double quotes. See herefor explanation

或者加双引号。看这里解释

for groupline in "$(cat file)"
do
        echo "$groupline";
done

without meddling with IFS, the "proper" way is to use while read loop

在不干预 IFS 的情况下,“正确”的方法是使用 while 读取循环

while read -r line
do
 echo "$line"
done <"file"

回答by Ignacio Vazquez-Abrams

Because you're doing it all wrong. You want whilenot for, and you want read, not cat:

因为你做的都是错的。你想whilefor,你想read,而不是cat

while read groupline
do
  echo "$groupline"
done < file

回答by Jiang Xin

The solution ghostdog74 providedis helpful, but has a flaw.

ghostdog74 提供的解决方案很有帮助,但有一个缺陷。

IFS could not use double quotes (at least in Mac OS X), but can use single quotes like:

IFS 不能使用双引号(至少在 Mac OS X 中),但可以使用单引号,例如:

IFS=$'\n'

It's nice but not dash-compatible, maybe this is better:

这很好,但不兼容破折号,也许这更好:

IFS='
'

The blank line will be eaten in the following program:

空行将在以下程序中被吃掉:

IFS='
'
for line in $(cat file)
do
        echo "$line"
done

But you can not add double quotes around $(cat file), it will treat the whole file as one single string.

但是您不能在 周围添加双引号$(cat file),它会将整个文件视为一个字符串。

for line in "$(cat file)"

If want blank line also be processed, using the following

如果还想处理空行,使用以下

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

回答by user3399273

Using IFS=$"\n"and var=$(cat text.txt)removes all the "n" characters from the output echo $var

使用IFS=$"\n"var=$(cat text.txt)从输出中删除所有“n”字符echo $var