Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace whole line containing a string using Sed

Tags:

string

shell

sed

I have a text file which has a particular line something like

sometext sometext sometext TEXT_TO_BE_REPLACED sometext sometext sometext 

I need to replace the whole line above with

This line is removed by the admin. 

The search keyword is TEXT_TO_BE_REPLACED

I need to write a shell script for this. How can I achieve this using sed?

like image 972
Rahul Avatar asked Jun 28 '12 12:06

Rahul


People also ask

How do you replace a whole line using sed?

The sed command can be used to replace an entire line with a new line. The "c" command to sed tells it to change the line. The sed command can be used to convert the lower case letters to upper case letters by using the transform "y" option.

How do you replace a line in a file using bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

You can use the change command to replace the entire line, and the -i flag to make the changes in-place. For example, using GNU sed:

sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo 
like image 112
Todd A. Jacobs Avatar answered Oct 15 '22 02:10

Todd A. Jacobs