All newlines are removed when saving cat output into a variable

左心房为你撑大大i 提交于 2020-12-29 02:43:09

问题


I have the following file

linux$ cat test.txt
toto
titi
tete
tata

Saving the cat output into a variable will discard the newlines

linux$ msgs=`cat test.txt`
linux$ echo $msgs
toto titi tete tata

How to keep the output containing the newlines in the variables?


回答1:


The shell is splitting the msgs variable so echo get multiple parameters. You need to quote your variable to prevent this to happen:

echo "$msgs"



回答2:


I had this:

echo $(cat myfile.sh) >> destination.sh

that was causing the problem, so I changed it to:

cat myfile.sh >> destination.sh

and that worked, lulz




回答3:


you can use the redirection "|"

echo | cat test.txt


来源:https://stackoverflow.com/questions/18018359/all-newlines-are-removed-when-saving-cat-output-into-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!