sed

Adding a new line before a pattern


I need to add some text before a pattern.

I know how can I add after the pattern.

sed  -i '/pattern/aNew Text'     input_file

But how to do it for adding the 'New Text' before the pattern.


Solution

  • The command to insert before is i (the one before "New Text", not the sed option):

    sed  -i '/pattern/iNew Text' input_file
    

    This command inserts what you want before the line that matches your pattern, but if you want to insert something before the match itself, use a replacement with a capture group.