Rao
Rao

Reputation: 1

bash compare two columns with exact match

I am comparing columns between two files for exact match but I am ending up with inaccurate result. Example as follows.

File1   File2
adam    sunny
jhon    adam
kelly   adam
matt    kevin
stuart  adam
Gary    Gary

When we look at the files there is only match i.e. Garry. My output should be following.

Emptyline
Emptyline
Emptyline
Emptyline
Emptyline
Gary 

In order to achieve requirement. I am running the following command

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

and I am getting output as follows

adam
adam
adam
Garry

Upvotes: 0

Views: 360

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133750

1st solution: With simple awk.

awk 'FNR==NR{a[FNR]=$0;next} a[FNR]==$0{print;next} {print ""}'  file1  file2

OR as per anubhava sir's comment:

awk 'FNR==NR{a[FNR]=$0;next} a[FNR]!=$0{$0=""} 1' file1  file2

Explanation: Adding detailed explanation for above code.

awk '              ##Starting awk program from here.
FNR==NR{           ##Checking condition FNR==NR which will be TRUE when first file Input_file1 is being read.
  a[FNR]=$0        ##Creating an array a with index FNR and value of current line here.
  next             ##next will skip all further statements from here.
}
a[FNR]==$0{        ##Checking condition if value of array a with FNR index and current line is equal then do following.
  print $0,a[FNR]  ##Printing current line and value array a with index FNR here.
}
'  file1  file2    ##Mentioning Input_file names here


2nd solution: Considering that your actual Input_file(s) have only 2 columns as per shown samples, could you please try following then.

paste Input_file1  Input_file2 | awk '$1==$2{print $1};$1!=$2{print ""}'

This code will only print lines whose values are equal in Input_file1 and Input_file2.

Upvotes: 1

Shawn
Shawn

Reputation: 52579

You should be tracking line numbers, not just line contents:

$ awk 'NR==FNR { lines[NR]=$0; next }
       { if ($0 == lines[FNR]) print; else print "" }' file1.txt file2.txt





Gary

Upvotes: 2

Related Questions