2

I'm trying to add a line at the beginning of a file, using

echo 'time/F:x1:x2' | cat - file.txt>newfile.txt

But this produces line breaks at each line in the new file (except for after the added 'time/F:x1:x2' line). Any ideas on how to avoid this?

pengwing
  • 73
  • 8
  • 3
    wait, what do you mean "produces line breaks at each line"? what does the input file look like and what does the output file look like? – glenn jackman Mar 18 '14 at 18:32
  • Sorry, this was badly phrased, I posed a new question http://stackoverflow.com/questions/22502013/unwanted-empty-lines-using-echo-and-cat @glennjackman – pengwing Mar 19 '14 at 09:55
  • Don't pose a new question; edit the old one. – kojiro Mar 19 '14 at 11:41

3 Answers3

2

Use -n to disable the trailing newline:

echo -n 'time/F:x1:x2' | cat - file.txt > newfile.txt

There are other ways, too:

sed '1s|^|time/F:x1:x2|' file.txt > newfile.txt
devnull
  • 118,548
  • 33
  • 236
  • 227
  • 2
    Or use `printf`: `printf "%s" 'time/F:x1:x2 | ... ` – Digital Trauma Mar 18 '14 at 18:32
  • Let me clarify: I should have written "empty lines", not "line break". So if my input is `line1 {linebreak} line2 {linebreak} line3` my output will be `time/F:x1:x2 {linebreak} line1 {linebreak} empty line {line break} line2 {line break} empty line {line break} line3` I want the first line break after time/F:x1:x2, but not the empty lines. – pengwing Mar 18 '14 at 20:59
1

How about

{ echo 'time/F:x1:x2'; cat file.txt; } >newfile.txt

or

sed '1i\
time/F:x1:x2' file.txt > newfile.txt
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

Actually you don't even need the echo and pipe if you're using bash. Just use a herestring:

<<< 'time/F:x1:x2' cat - file.txt > newfile.txt
kojiro
  • 74,557
  • 19
  • 143
  • 201