Compare two files and list common lines

You can use the awk command to compare two files and show the common ones. Compared to the Linux command “comm”, advantages of using “awk” is it will give output though the files are not sorted.
Syntax :

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

Eg :

[root@test]# cat A
apple
orange
mango
grape

[root@test]# cat B
mango
banana
grape

[root@test]# awk 'NR==FNR{a[$1]++;next} a[$1] ' A B
mango
grape
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s