Thursday, November 18, 2021

[SOLVED] grep remove exact matches from line without removing the whole line

Issue

I have patterns.txt file and I would like to remove all exact matches of patterns from FILE.txt. The FILE.txt is the following:

word1 word2
word3 word4
word5 word6

The pattern file contains:

word1
word6

The expected output is:

word2
word3 word4
word5

The command below removes the whole row where there is an exact match. How can I only remove the exact match from a line without removing the whole line? I don't want to use for-loops to achieve this.

cat FILE.txt | grep -wvf pattern.txt

Solution

With sed:

re=$(tr '\n' '|' < patterns.txt)
sed -r "s/$re//; s/^[[:space:]]*//" file
word2
word3 word4
word5 

Note: Make sure patterns.txt does not have a trailing new line or extra new lines since | will end up in each of those positions.



Answered By - dawg