sed: Insert multiple lines before or after pattern match

Here our requirement is to add multiple lines after a pattern is matched in a newline which can be before or after the match based upon the requirement

Below is our sample file /tmp/file

This is line one
This is line two
This is line three
This is line four

Here in we have to put below content

your text 1
your text 2
your text 3

as per below requirement

  • one line before the string is matched
  • one line after the string is matched

Example 1
Here we will add our content one line before the string is matched

Solution

# sed '/This is line two/iyour text 1nyour text 2nyour text 3' /tmp/file
This is line one
your text 1
your text 2
your text 3
This is line two
This is line three
This is line four

Example 2
Here we will add our content one line after the string is matched

Solution

# sed '/This is line two/ayour text 1nyour text 2nyour text 3' /tmp/file
This is line one
This is line two
your text 1
your text 2
your text 3
This is line three
This is line four

How to do "in place" replacement in a file?

This can be done using "-i" flag with sed command as shown in below example.

# sed -i '/This is line two/ayour text 1nyour text 2nyour text 3' /tmp/file

IMPORTANT NOTE: Do not use in place replacement this unless you are very sure the command will not impact anything else, it is always recommended to use "i.bak" which will take a backup of the target file before doing the in place replacement

# sed -i.bak '/This is line two/ayour text 1nyour text 2nyour text 3' /tmp/file

I hope the article was useful.

1 thought on “sed: Insert multiple lines before or after pattern match”

  1. Hello All,
    I have following file contents in abc file.
    I would like to comment line
    # atrium_package: “234”
    and insert a new line
    atrium_package: 456
    abc file
    ——–
    1
    2
    .
    .
    .
    N number of lines
    # Product and version to install
    # atrium_package: “123”
    atrium_package: “234”
    .
    .
    Output should look like:
    ————————
    1
    2
    .
    .
    .
    N number of lines
    # Product and version to install
    # atrium_package: “123”
    # atrium_package: “234”
    atrium_package: 456
    .
    .
    .

    Reply

Leave a Comment