Thursday, September 16, 2010

Comparing two files in Unix

You got 2 files which contains a list of servernames (as shown below). You want to compare the entries between two files and get the list of server names which aren’t present in both files:

1st file:
server_a
server_b
server_c
server_d
server_e

2nd file:
server_c
server_d
server_g
server_a

Output should be:

server_b
server_g
server_e



Solution 1:  
# sort file1 file2 | uniq –u

Solution 2:
# sort file1 > file1.sorted
# sort file2 > file2.sorted
# comm -3 file1.sorted file2.sorted

No comments:

Post a Comment