Monday, February 26, 2024
rated 0 times [  146] [ 0]  / answers: 1 / hits: 356872  / 2 Years ago, mon, march 14, 2022, 1:10:37

How to remove all the lines from the text file containing the words "cat" and "rat"?

More From » command-line


grep approach

To create a copy of the file without lines matching "cat" or "rat", one can use grep in reverse (-v) and with the whole-word option (-w).

grep -vwE "(cat|rat)" sourcefile > destinationfile

The whole-word option makes sure it won't match cats or grateful for example. Output redirection of your shell is used (>) to write it to a new file. We need the -E option to enable the extended regular expressions for the (one|other) syntax.

sed approach

Alternatively, to remove the lines in-place one can use sed -i:

sed -i "/(cat|rat)/d" filename

The  sets word boundaries and the d operation deletes the line matching the expression between the forward slashes. cat and rat are both being matched by the (one|other) syntax we apparently need to escape with backslashes.

Tip: use sed without the -i operator to test the output of the command before overwriting the file.

(Based on Sed - Delete a line containing a specific string)

[#29130] Tuesday, March 15, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 335
Total Questions: 111
Total Answers: 119

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago