How do I Find a string in a file and place a string above it? 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 's/__MARKER__/Hello world\n__MARKER__/' someFile.txt


However, after running the above snippet, the contents of someFile.txt is below:

Hello worldn__MARKER__


Contents of someFile.txt before manipulation:

__MARKER__


Contents of someFile.txt after manipulation:

Hello World!
__MARKER__
s/…/…/ is a substitution, replacing the first … with the second …. You can use a new line in your string to insert text above or below a line break.



sed -i -e 's/__MARKER__/Hello world\
__MARKER__/' someFile.txt


Escape the new line with a backslash, else you'll get "unescaped newline inside substitute pattern". To type a new line in Terminal, use ⌥↩︎.

You can use &amp; as shorthand for the match, so you don't need to retype it in the replacement.

sed -i -e 's/__MARKER__/Hello world\
&amp;/' someFile.txt