I would like to find the String __MARKER__ in someFile.txt and place a String above it (e.g. Hello World!).

How would I do that using sed?

sed -i -e "/__MARKER__//g" someFile.txt # Currently removes __MARKER__.

Contents of someFile.txt:


Contents of someFile.txt after manipulation:

Hello World!
sed -i -e 's/__MARKER__/Hello world\n&/' someFile.txt

replaces __MARKER__ with Hello world, a newline, and the match (&), i.e. the text __MARKER__.

The & just saves typing __MARKER__ again, as in

sed -i -e 's/__MARKER__/Hello world\n__MARKER__/' someFile.txt
  • After running sed -i -e 's/__MARKER__/Hello world\n&/' someFile.txt the contents of someFile.txt is Hello worldn__MARKER__. – Nicholas Adamou Jun 6 '18 at 19:46
  • 2
    That's weird because for me it works exactly as I've written and I didn't escape any backslashes (by doubling them). It just worked as is. Are you on Windows? – PerlDuck Jun 6 '18 at 19:51

If there is only a single instance of __MARKER__ or you want to insert the new string before every instance, you can use

sed -i '/__MARKER__/ iHello World!' someFile.txt

This uses the insert command rather than the substitute command - note that on POSIX (non-GNU) sed you may need to put the insert string on a separate line:

sed -i '/__MARKER__/ i\
Hello World!
' someFile.txt

If there are multiple instances, and you only wish to insert the string before the first one, then

sed -i '0,/__MARKER__/ s//Hello World!\n&/' someFile.txt

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.