3

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__
3

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
  • What if someFile.txt has // __MARKER__ in it? Notice the //. Do I have to escape it? – Nicholas Adamou Jun 6 '18 at 20:38
  • @Nicholas Then you'll get // Hello world followed by __MARKER__ on the line after. I'm not sure what you're referring to with escaping //, the substitution purely looks for the marker string and replaces it with the substitution. – grg Jun 6 '18 at 20:40
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .