Bash - find a keyword in a file and delete its line [duplicate] Bash - find a keyword in a file and delete its line [duplicate] bash bash

Bash - find a keyword in a file and delete its line [duplicate]


Use the stream editor, sed:

sed -i ".bak" '/culpa/d' test.txt

The above will delete lines containing culpa in test.txt. It will create a backup of the original (named test.txt.bak) and will modify the original file in-place.


Pipe it to another file, not the same one that you're reading from, and be careful with the useless use of cat.

grep -v "$KEYWORD" /etc/hosts > newfile

Apart from the fine answer given regarding sed, you can also use Perl and a little improved regex to solve this:

perl -pi.old -e 's/.*\sdomain\.com\s*\n//' file

Notice I'm considering domain.com will be isolated by space characters (tabs or spaces, and so on), and that nothing but zero or more spaces will appear after it until the newline. Similarly to -i in sed,
-i.old in perl sets the $^I variable, and your original file will receive the changes while a copy will be kept under the old name and a .old appended.


If you want to only delete last line of your example file

sed -i '/[[:space:]]\+domain\.com/d' test.txt