DomainsFeatured DomainsFeatured - 2 months ago 6
Linux Question

Replace All Lines That Do Not Contain Matched String

I'm working with this file of data that looks like this:

text in file
hello random text in file
example text in file
words in file hello
more words in file
hello text in file can be
more text in file


I'm trying to replace all lines that do not contain the string
hello
with
match
using sed, so the output would be:

match
hello random text in file
match
hello words in file
match
hello text in file can be
match


I tried using
sed '/hello/!d'
but that deletes the line. Also, I read that I can match using
!
within sed but I'm not sure how to match every line and replace properly. If you could give me some direction, I would really appreciate it.

Answer

You can do it like this:

$ sed '/hello/!s/.*/match/' infile
match
hello random text in file
match
words in file hello
match
hello text in file can be
match

/hello/! makes sure we're substituting only on lines not containing hello (you had that right), and the substitution then replaces the complete pattern space (.*) with match.