Re: Match two files (265 Views)
Reply
Advisor
Posts: 25
Registered: ‎10-24-2011
Message 1 of 3 (282 Views)

Match two files

I have two files , the content is as below , I would like to list the lines in file2 , that the lines the file1 have , as the below , both files have aaaa , cccc , eeee , so the output is the line which have aaaa , cccc , eeee , can advise what can i do ? thx

file1
=====
aaaa
bbbb
cccc
dddd
eeee


file2
=====
aaaa 1111
cccc 2222
eeee 3333


my desired result is as below
=============================
aaaa 1111
cccc 2222
eeee 3333

Acclaimed Contributor
Posts: 25,717
Registered: ‎03-06-2006
Message 2 of 3 (269 Views)

Re: Match two files

You can simply use: fgrep -f file1 file2

 

if you are worried about substrings in file1 that may match multiple lines in file2, you can add -w:

grep -w -f file1 file2

Valued Contributor
Posts: 60
Registered: ‎10-09-2011
Message 3 of 3 (265 Views)

Re: Match two files

Hi There, you can try this with awk:

 

$ awk 'NR==FNR {a[$1]=$1;next} {print a[$1],$2}' file1 file2

 

Cheers,

Raj D.

The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.