Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace whole line when match found with sed

I need to replace the whole line with sed if it matches a pattern. For example if the line is 'one two six three four' and if 'six' is there, then the whole line should be replaced with 'fault'.

like image 211
irek Avatar asked May 08 '13 12:05

irek


People also ask

How do you replace a line using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.

Which sed command is used for replacement?

The s command (as in substitute) is probably the most important in sed and has a lot of different options. The syntax of the s command is ' s/ regexp / replacement / flags '.

How do you sed a line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

How do I replace a line in a bash script?

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.


2 Answers

You can do it with either of these:

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

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

Example:

$ cat file six asdf one two six one isix boo $ sed 's/.*six.*/fault/'  file fault asdf fault fault boo 

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 
like image 185
fedorqui 'SO stop harming' Avatar answered Sep 22 '22 10:09

fedorqui 'SO stop harming'


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 
like image 27
Hasan Rumman Avatar answered Sep 19 '22 10:09

Hasan Rumman