Dr Jay
Dr Jay

Reputation: 425

sed delete lines matching pattern between 2 files

Hey i'm still a beginner on sed and i'm trying to sed script to only output the lines not found of 1.txt to 2.txt if the line has the /pattern/ . I have the following :

1.txt
[email protected]:boo
[email protected]:foo
[email protected]:foo

2.txt
@example.de
@example.com

The desired output would be

[email protected]:foo

I've tryed those commands looks not working

$ grep -f 2.txt 1.txt
$ cat 2.txt | xargs -I {} sed -n "/{}/p" 1.txt

Upvotes: 1

Views: 85

Answers (2)

oguz ismail
oguz ismail

Reputation: 50815

You can do this using following awk command.

awk -F '[@:]' 'NR == FNR { blacklist[$2]; next } !($2 in blacklist)' 2.txt 1.txt

Explanation:

  • -F '[@:]' tells awk that fields in input lines are separated by a @ or :. ([email protected]:foo -> $1 = demo, $2 = example.com, $3 = foo)
  • NR == FNR <action> means do the following action only while processing the first file given as an argument to awk.
  • blacklist[$2] registers a key in array blacklist with the domain name in the current line.
  • next means skip to next line.
  • !($2 in blacklist) means print the current line if the domain name in it does not exist in array blacklist.

Upvotes: 3

anubhava
anubhava

Reputation: 786349

You can use -v option of grep, no need to use sed:

grep -vFf 2.txt 1.txt

[email protected]:foo

Upvotes: 3

Related Questions