Skip to main content

Use sed to insert lines before or after a match

Given a file, FILE, containing this content:

# Header 1 - Primary

Some detail

then this sed command will append (in place) AFTER the line containing # Header 1 - Primary the text \n## Section Header (note the leading linefeed which needs to be escaped):

sed -i '/# Header 1.*/a \\n## Section Header' FILE

resulting in

# Header 1 - Primary

## Section Header

Some detail

To insert BEFORE the matched text, use the switch /i instead.

To do only ONE replacement,

sed -i '0,/# Header 1.*/a \\n## Section Header' FILE

See here for more detail and examples using sed.