3

I have a text file and I want to prepend some text to the first line. I tried something like this:

sed -i '1i\'"string" file

However this inserts a new line to the text file.

6

This should work with GNU sed:

sed -i '1s/^/string/' file

it's different from your solution in not adding the new line.

test

Before running command, the content of file is this:

some
text
here
already

After running the command:

stringsome
text
here
already
| improve this answer | |
  • 1
    @lese if you remove the \n from your command I think it answers the question, OP is looking for text in front of their first line rather than a new first line. – Centimane Oct 29 '15 at 10:16
1

Another way (similar to my answer in this question):

printf 'string' | paste -d'\0' - infile > outfile

or:

printf string | cat - infile > outfile

or:

{ printf string; cat infile; } > outfile
| improve this answer | |
  • @StéphaneChazelas: Yep, or without subshell { printf string; cat infile; } > outfile – cuonglm Jul 18 '16 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.