Remove entire line containing string in a file

Q I need to grep for a particular 'string' in a file and remove the entire line where the occurrence of the string is found. I want it to work across with a collection of files. Can you help?

A It is possible to use grep for this: grep -v string file will output all lines that do not contain the string. But sed is a more suitable tool for batch editing.

sed --in-place '/some string/d' myfile

will delete all lines containing 'some string' To process a collection of files, you need to use a for loop (or find) because sed 's --in-place option only works on single files. One of these commands will do it:

for f in *.txt; do sed --in-place '/some string/d'
"$f"; done
find -name '*.txt' -exec sed --in-place=.bak '/some
string/d' "{}" ';'

Adding =.bak in the latter example makes sed save a backup of the original file before modifying it.

Follow us on or Twitter

Username:   Password: