16

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?

2 Answers 2

15

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
2
  • thanks! when i use the second option i get: sed: -e expression #1, char 0: unmatched `{'
    – clamp
    Feb 24, 2012 at 10:34
  • at the end of the first line, you need to type \ and then hit Return - it's important that the \ escapes that first newline. Then, make sure the }' is on a seperate line from another string: the replacement is everything on that second line, including the } if you put it there.
    – Useless
    Feb 24, 2012 at 12:44
3

You can use inplace functionnality of sed :

sed -i -e 's/foo/bar/' myfile.txt
2
  • 1
    This will only replace every foo with bar not the whole line..
    – Jahid
    Jun 13, 2015 at 19:38
  • 1
    funny enough, I did multiple searches and this question came up as my top result hence for some reason even though the question is to replace the full line I still believe that this answer helps other lost souls out there. I'd update your comment to clarify and leave the original response.
    – saul
    Oct 20, 2020 at 18:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .