Monday, December 1, 2014

Intersect two files using sort and uniq commands

If you have two lists that you want to intersect, use sort and uniq commands to easily perform this operation.

For examle, file1 contains:

ZXDB
ZYG11A
ZYG11B
ZYX
ZZZ3

file2 contains:

ZSWIM7
ZSWIM8
ZWILCH
ZXDB
ZYG11A
ZYG11B

Command:

sort file1 file2 | uniq -d

will print strings that are same for the two files. (sort will use both files as input and uniq -d option will print only duplicates)

ZXDB
ZYG11A
ZYG11B

On the other side, command:

sort file1 file2 | uniq -u

will print only uniq lines after sorting two files together (i.e. these are unique lines from both files):

ZSWIM7
ZSWIM8
ZWILCH
ZYX
ZZZ3

No comments:

Post a Comment