Anouar
Anouar

Reputation: 13

Diff between 2 files (awk)

I tried a number of solutions from Stack Overflow, but without a favourable result. I have 2 files and want to remove the entries from file1 that are mentioned in file2.

File1

1,[email protected],9
9,[email protected],1
8,[email protected],6
2,[email protected],1
15,[email protected],3
6,[email protected],1

File2

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

Result

1,[email protected],9
8,[email protected],6
2,[email protected],1
6,[email protected],1

Could you help me please? My failed attempt:

awk -F',' 'NR==FNR{c[$1]++;next};c[$2] > 0' file2 file1

Upvotes: 0

Views: 113

Answers (3)

karakfa
karakfa

Reputation: 67497

since if there is no chance of false positives, this might be the easiest

$ grep -vf file2 file1      

1,[email protected],9   
8,[email protected],6 
2,[email protected],1 
6,[email protected],1   

a better idea is to change to fixed strings (instead of pattern matching)

$ grep -vfF file2 file1

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133518

try following awks and let me know if this helps you.

Solution 1st:

awk 'FNR==NR{a[$0];next} ($2 in a){next} 1' File2 FS="," File1

Solution 2nd:

awk 'FNR==NR{a[$0];next} !($2 in a)' File2 FS="," File1

Upvotes: 1

user31264
user31264

Reputation: 6727

Here is my awk file which does this:

FNR==1 {NFILE++}

NFILE==1 {a[++n]=$0}

NFILE==2 {b[$0]}

END {for (i=1; i<=n; i++) if (!(a[i] in b)) print(a[i])}

It prints all lines of file1 which are NOT in file2, as per your example.

Upvotes: 1

Related Questions