0

Consider I have two text files.

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

sale@gmail.com
info@yahoo.com
all@gmail.com
help@domain.com
abcdsale@gmail.com
abcd.info@yahoo.com

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

sale@
info@
all@
help@

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:

abcdsale@gmail.com
abcd.info@yahoo.com

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.

0
2

The second file should look like this:

^sale@
^info@
^all@
^help@

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.

4
  • Perfect! This works great. :) – Joney Walker Jan 28 '19 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 $? – Joney Walker Jan 28 '19 at 11:32
  • @JoneyWalker No, you probably want $. Please research regular expressions. – Kamil Maciorowski Jan 28 '19 at 11:38
  • Ok got it... This works: grep -vf <(sed 's/$/$/' Test2.txt) Text1.txt – Joney Walker Jan 28 '19 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.