sed: match string and append new line (before or after)

Before is the requirement for this example.

I have a sample file with below content at /tmp/file
This is line one
This is line two
This is line three
This is line four
Here in we have to put our content "your text" at

  1. one line before the string is matched 
  2. one line after the string is matched

Example 1
Here I want to put my content before "This is line two"

Solution
# sed '/This is line two/iyour text' /tmp/file

This is line one
your text
This is line two
This is line three
This is line four
To perform in place operation
# sed -i '/This is line two/iyour text' /tmp/file
Example 2
Here I want to put my content after "This is line two"

Solution
# sed '/This is line two/ayour text' /tmp/file

This is line one
This is line two
your text
This is line three
This is line four
To perform in place operation
# sed -i '/This is line two/ayour text' /tmp/file

IMPORTANT NOTE :  Do not use this unless you are very sure the command will not impact anything else, it is always recommended to take a backup of such file where you plan to do in place replacement

Leave a Comment

close button