0

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

Community
  • 1
  • 1
pengwing
  • 73
  • 8
  • 2
    I tried your command under bash & zsh, the problem cannot be reproduced here. your command gave the expected result. – Kent Mar 19 '14 at 10:00
  • 2
    You asked [this earlier](http://stackoverflow.com/questions/22487023/unwanted-line-break-using-echo-and-cat) too. Why not update your previous question instead of posting a new one? – devnull Mar 19 '14 at 10:00
  • I am getting the desired output on running the command. – myusuf Mar 19 '14 at 10:05
  • Yes, I should have edited the old one, I'm new to Stackoverflow and didn't know this was possible (and didn't find the button at the time). However, I don't agree this is a duplicate, since the bad phrasing of the former indicated another problem than the one I actually have (namely empty lines, and not line breaks). – pengwing Mar 20 '14 at 09:35

2 Answers2

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
Peder Klingenberg
  • 37,937
  • 1
  • 20
  • 23
  • Yes, this must be the case, the text files were produced in Windows. When only replacing lines (that is, not adding one with \n at the end) with sed this problem did not occur. Any idea about how to get around this? – pengwing Mar 20 '14 at 09:41
  • Okay, so I could now solve this by converting the files to Unix format. – pengwing Mar 20 '14 at 11:32
1

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
slayedbylucifer
  • 22,878
  • 16
  • 94
  • 123