Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a line at the beginning of a file with sed?

Tags:

sed

Im trying to insert a line containing these characters: ~o to the beginning of a file. Im using: sed -i '' "1s/^/~o \n/" macros But the newline option just doesn't do its job. How should I change it ? Thank you

like image 201
KianStar Avatar asked Nov 06 '25 12:11

KianStar


1 Answers

You can use the insert command i:

sed '1i\TEXT TO INSERT' file

Explanation:

1     Addresses the first line
i     The insert command inserts the following
      text before(!) line 1
\     Required after i (in POSIX compatible versions of sed)
TEXT  The text to insert

Example:

sed '1i\Hello' <<< 'world!'

Output:

Hello
world!

Btw, i works even with newline characters:

sed '1i\Hello\n' <<< 'world'

Output:

Hello

world!
like image 148
hek2mgl Avatar answered Nov 09 '25 09:11

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!