Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

shell - 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'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...