1

I am trying to insert a line in the beginning of a file using sed. I tried below commands :

sed -i '1s/^/LINE TO INSERT\n/' test.txt sed: illegal option -- i --> Error thrown

sed '1i/^/LINE TO INSERT\n/' test.txt sed: Function 1i/^/LINE TO INSERT\n/ cannot be parsed. --> Error thrown

Both the ways came out to be failed. Any possible solution to it ? I am using ksh script on HP-UX.

Thanks.

Ritesh
  • 314
  • 7
  • 19
  • 1
    Why don't you `echo "LINE TO INSERT" > tmp_file.txt` then `cat test.txt >> tmp_file.txt` and finally `mv tmp_file.txt test.txt`? – fedorqui May 24 '16 at 10:35

2 Answers2

3

How about good old ed?

printf '%s\n' 1i 'LINE TO INSERT' . w | ed -s file

printf is used to send each command to ed on a separate line.

Alternatively, if you're terrified of ed like me, you can just use a temporary file, as suggested in the comments:

echo 'LINE TO INSERT' > tmp && cat tmp test > new && mv new test && rm tmp
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2

I think you have a typo: you're missing the closing apostrophe from your 1st command. Otherwise it's fine. I.e.:

You have this: sed -i '1s/^/... test.txt

But you need this: sed -i '1s/^/...' test.txt

Putting all together: sed -i '1s/^/LINE TO INSERT\n/' test.txt

Update: if -i is not supported, then you can use a temporary file:

sed '1s/^/LINE TO INSERT\n/' test.txt > /tmp/test.txt.tmp
mv /tmp/test.txt.tmp test.txt
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
  • 1
    The version of `sed` on this system is very unlikely to support `-i`, so this won't help. – Tom Fenech May 24 '16 at 10:59
  • Well ,last one worked , but it is appending 'n' after the line. How to avoid it ? Thanks – Ritesh May 24 '16 at 13:04
  • 1
    I can only give suggestions since I have different environment. According to this page: http://www.tek-tips.com/viewthread.cfm?qid=1184966 you could replace `\n` with `^M` in your sed command: `sed '1s/^/LINE TO INSERT^M/' ...` – Tamas Rev May 24 '16 at 13:42