Replace whole line when match found with sed Replace whole line when match found with sed shell shell

Replace whole line when match found with sed


You can do it with either of these:

sed 's/.*six.*/fault/' file     # check all linessed '/six/s/.*/fault/' file     # matched lines -> then remove

It gets the full line containing six and replaces it with fault.

Example:

$ cat filesixasdfone two sixone isixboo$ sed 's/.*six.*/fault/'  filefaultasdffaultfaultboo

It is based on this solution to Replace whole line containing a string using Sed

More generally, you can use an expression sed '/match/s/.*/replacement/' file. This will perform the sed 's/match/replacement/' expression in those lines containing match. In your case this would be:

sed '/six/s/.*/fault/' file

What if we have 'one two six eight eleven three four' and we want to include 'eight' and 'eleven' as our "bad" words?

In this case we can use the -e for multiple conditions:

sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' file

and so on.

Or also:

sed '/eight/s/.*/XXXXX/; /eleven/s/.*/XXXX/' file


Above answers worked fine for me, just mentioning an alternate way

Match single pattern and replace with a new one:

sed -i '/six/c fault' file

Match multiple pattern and replace with a new one(concatenating commands):

sed -i -e '/one/c fault' -e '/six/c fault' file


This might work for you (GNU sed):

sed -e '/six/{c\fault' -e ';d}' file

or:

sed '/six/{c\fault'$'\n'';d}' file