scripting - number - sed insert text after match




Using sed, Insert a line below(or above) the pattern? (3)

Insert a new verse after the given verse in your stanza:

sed -i '/^Hello My love, you're dirty girl$/ s:$:\nI know, I am, my sexy knight:' FILE

This question already has an answer here:

I need edit a good number of files, by inserting (2) lines either right below a unique pattern or above it. please advise how to do it using sed, awk, perl or anything else in shell. thanks

some text
Hello My love, you're dirty girl
more text

I want to insert 'I know, I am, my sexy knight' after ' Hello My love, you're dirty girl', so output file will look like

some text
Hello My love, you're dirty girl
I know, I am, my sexy knight
more text

More portable to use ed; some systems don't support \n in sed

printf "/^Hello My love, you're dirty girl/a\nI know, I am, my sexy knight\n.\nw\nq\n" |\
    /bin/ed $filename

To append after the pattern: (-i is for inplace replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile




awk