How do I Find a string in a file and place a string above it?

Solution 1:

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 & as shorthand for the match, so you don't need to retype it in the replacement.

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

Solution 2:

Another option, is sed's insert function.

input:

cat someFile.txt

output:

apple
orange
grape
pineapple
plum
_MARKER_
banana


input:

sed '/_MARKER_/i\
Hello World!
' someFile.txt

output:

apple
orange
grape
pineapple
plum
Hello World!
_MARKER_
banana