Unwanted empty lines using echo and cat [duplicate

2019-08-26 09:09发布

This question already has an answer here:

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.]

标签: bash echo cat
2条回答
做个烂人
2楼-- · 2019-08-26 09:52

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
查看更多
别忘想泡老子
3楼-- · 2019-08-26 09:56

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
查看更多
登录 后发表回答