4

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.

0

2 Answers 2

8

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
1
  • 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, 2015 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
1
  • @StéphaneChazelas: Yep, or without subshell { printf string; cat infile; } > outfile
    – cuonglm
    Jul 18, 2016 at 17:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .