Unwanted empty lines using echo and cat [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-25 06:29:11

问题


I want to add a line to the beginning of a text file. I have input.txt:

line1
line2
line3

and want to add the line 'time/F:x1:x2' to end up with

time/F:x1:x2
line1
line2
line3

I'm trying to do this with

echo 'time/F:x1:x2' | cat - input.txt>output.txt

but what I get is

time/F:x1:x2
line1

line2

line3

that is, I get empty lines I don't want. How can I avoid this? [edit: This is not a duplicate of Unwanted line break using echo and cat since I wrongly asked about line breaks there - what I really want to avoid is empty lines.]


回答1:


Perhaps your original file has MS-DOS line endings (\r\n), and whatever you use to display the file is smart enough to detect that. Then, when you add a line with unix line ending (\n) to the top, the detection breaks, and you get shown the blank lines inbetween.

Edit There are myriads of ways to convert line endings. Most editors can do it for you interactively. In your case, you can for instance extend your pipeline with

| tr -d '\r' > output.txt



回答2:


I want to add a line to the beginning of a text file.

How about this:

$ cat test 
line1
line2
line3

$ sed -i '1i time/F:x1:x2' test 

$ cat test 
time/F:x1:x2
line1
line2
line3


来源:https://stackoverflow.com/questions/22502013/unwanted-empty-lines-using-echo-and-cat

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