How to remove all the lines from the text file containing the words "cat" and "rat"?
Ubuntu – How to remove lines from the text file containing specific words through terminal
command linetext processing
Related Question
- Ubuntu – How to delete words from txt file, that exists on another txt file
- Ubuntu – How to remove domain part of each line from text file containing email addresses
- Ubuntu – How to remove all lines in a file that are less than 6 characters
- Ubuntu – Text between 2 words with some lines before patterns
- Ubuntu – Delete all lines containing backslash from text file
- Ubuntu – command to remove specific string from multiple files
- Ubuntu – How to remove particular words from lines of a text file
Best Answer
grep
approachTo 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
).The whole-word option makes sure it won't match
cats
orgrateful
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
approachAlternatively, to remove the lines in-place one can use
sed -i
:The
\b
sets word boundaries and thed
operation deletes the line matching the expression between the forward slashes.cat
andrat
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)