0

Consider I have two text files.

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

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

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:

[email protected]
[email protected]

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

1 Answer 1

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. :) Commented 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 $? Commented Jan 28, 2019 at 11:32
  • @JoneyWalker No, you probably want $. Please research regular expressions. Commented Jan 28, 2019 at 11:38
  • Ok got it... This works: grep -vf <(sed 's/$/$/' Test2.txt) Text1.txt Commented Jan 28, 2019 at 11:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .