Home > Enterprise >  Compare two files in linux?
Compare two files in linux?

Time:09-25

I have two files that i am trying to compare. File1.txt and File2.txt. File1.txt looks like :-

name1 12.12.365.237
name2 12.90.543.87
name3 34.47.26.230
name4 11.10.90.234
name5 10.11.12.15

Whereas my file2 looks like :-

10.11.12.15
12.12.365.237
11.10.90.234

I am trying to write a script to identify which IP addresses are in file1 which are not present in file2 and output the name and the IP in a separate file and convert it into CSV. so the desired output will be :-

name2 12.90.543.87
name3 34.47.26.230  

I tried using grep like this :-

grep -Fxvf File2.txt File1.txt >> not-in-File2.txt

mv not-in-File2.txt not-in-File2.csv

But the grep command doesn't seem to be working as it gives the wrong output.It currently gives me the entire file1 as it is.

name1 12.12.365.237
name2 12.90.543.87
name3 34.47.26.230
name4 11.10.90.234
name5 10.11.12.15

What would be the best way to compare these 2 files?

CodePudding user response:

Your approach of using grep -x won't work because it is looking for an exact match whereas file1 has 2 columns but file2 has only one. By removing -x it will give output but will output full lines not just the IPs e.g.:

grep -vwFf file2 file1

name2 12.90.543.87
name3 34.47.26.230

To get just the IPs you will have to use:

grep -vwFf file2 file1 | cut -d ' ' -f2

-w is very important here otherwise grep won't detect mismatch between 12.12.365.237 and 12.12.365.23.


You may use this better solution using awk:

awk 'FNR == NR {ips[$1]; next} !($2 in ips) {print $2}' file2 file1

12.90.543.87
34.47.26.230

CodePudding user response:

OP probably wants to enforce an exact word match instead of an exact line match, so replace the -x with a -w (same thing anubhava has mentioned):

$ grep -Fwvf File2.txt File1.txt
name2 12.90.543.87
name3 34.47.26.230 
  • Related