Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare each row of one file with each row of another file

Tags:

bash

awk

I have two files:

file1

cat file1
A,1
B,2
C,2
D,3

file2

cat file2
A
A
A
B
B
C
C
D

Desired output

cat output
A,A,1 
A,A,1
A,A,1
B,B,2
B,B,2
C,C,2
C,C,2
D,D,3

As you can see, each line of file1 should be matched with each line of file2 and if they match, the line from file1 should be added to the matched line in file2. I have tried join but it doesn't work. I guess the search needs to be recursive but I am not sure how to do it when two files are involved.

Any help would be greatly appreciated.

Thanks

like image 620
rohit Avatar asked Dec 11 '25 10:12

rohit


2 Answers

Using awk:

awk -F, -v OFS=, 'FNR==NR {a[$1]=$0;next} $1 in a{print $1, a[$1]}' file1 file2
A,A,1
A,A,1
A,A,1
B,B,2
B,B,2
C,C,2
C,C,2
D,D,3
like image 81
anubhava Avatar answered Dec 13 '25 00:12

anubhava


join -t',' -o'1.1,2.1,2.2' file2 file1

this line does it.

like image 23
Kent Avatar answered Dec 13 '25 01:12

Kent