Question

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

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top