Consider I have two text files.

First File name - "Emails.txt" with the following data:


Second text file - "Roles.txt" with the following strings:


How to delete all the lines in the 1st text file "Emails.txt" if it matches ONLY EXACT stings of any line present in the second text file "Role.txt"?

The desired output of the new file should be:


I tried using

grep -vf Role.txt Emails.txt

But, this command also deletes the line if it matches all the characters of the Role.txt.

I want to remove only it matches EXACT as per Role.txt file, and swip everything if there are other characters before the desired string.

Here someone gave a similar solution for removing line matching EXACT string at the end of each lines, but in this I need the regrex to so the same at the beginning of each lines.


1 Answer 1


The second file should look like this:


because ^ matches the beginning of a line.

You can rebuild the file with sed -i 's/^/^/' Role.txt. To be clear: this will change the file. Then your original command

grep -vf Role.txt Emails.txt

will work.

Alternatively, with your original Role.txt, in a shell that supports process substitution (e.g. Bash):

grep -vf <(sed 's/^/^/' Role.txt) Emails.txt

In this case sed adds ^ characters on the fly and Role.txt remains unchanged.

  • Perfect! This works great. :) Jan 28, 2019 at 10:57
  • So if I want to do the same at the end of file, will this work if i add ^ at the end of line too? eg: @domail.co^ such that @domain.co.uk will be skipped? or should we substitute the end with $? Jan 28, 2019 at 11:32
  • @JoneyWalker No, you probably want $. Please research regular expressions. Jan 28, 2019 at 11:38
  • Ok got it... This works: grep -vf <(sed 's/$/$/' Test2.txt) Text1.txt Jan 28, 2019 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.