sed :Replace whole line when match found

Here our requirement is to replace a line with our content when a match is found with in the file

Our sample file /tmp/file
This is line one
This is line two
This is line three
This is line four
Here we will search for line having the string “two” and replace the complete line with “your text
# sed ‘/two/cyour text’ /tmp/file

This is line one
your text
This is line three
This is line four
To do in place replacement in the same file

# sed -i ‘/two/cyour text’ /tmp/file
Similarly if you want to match the line having the string “three” and replace the line with “your text
# sed ‘/three/cyour text’ /tmp/file
This is line one
This is line two
your text
This is line four
To do in place replacement in the same file
# sed -i ‘/three/cyour 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