Grep: search and replace full line

greptext processing

The command

 grep "foo" myfile.txt

prints all matching lines in my file.

Now I want to replace the full line with another string. How can I do that?

Best Answer

If you're matching a substring of the whole line, you can either use sed's s command with a regex to mop up the rest of the line:

sed -i 's/^.*foo.*$/another string/' myfile.txt

or use the c command to replace the matched line in one go:

sed -i '/foo/ { c \
another string
}' myfile.txt

If you don't want to type multiline commands at the prompt, you can put it in a script instead:

$ cat foo.sed
/foo/ { c \
another string
}

$ sed -i -f foo.sed myfile.txt
Related Question