Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Given two files, I want to write a shell script that reads each line from file1 and checks if it is there in file2. If a line is not found in file2 it should keep it lets say in a table TAB1. Also, if there any any additional lines in file2, which are not in file 2 it should keep it lets say in a table TAB2.

The files can contain words numbers or anything. For example :

file1 :

Hi!
1234
5678
1111
hello

file2:

1111
5678
1234
Hi!
hellothere

In this case there should be "hello" in TAB1, and "hellothere" in TAB2

If two files are equal I want to return with "files are equal" echo or something like that.

How can I do this? I've tried experimenting with diff, but without success.

Thanks in advance

share|improve this question

1 Answer 1

up vote 0 down vote accepted

First you need to sort each file. Then you need to use comm. Finally you can extract the columns that comm produces using awk. So something like this.

#! /bin/bash
sort $1 > $1.sorted
sort $2 > $2.sorted
comm -3 $1.sorted $2.sorted > columns
if [ -s columns ]; then
  TAB1="$(awk '{ print $1 }' < columns)"
  TAB2="$(awk '{ print $2 }' < columns)"
  # do something with TAB1 and TAB2
else
  echo $1 and $2 contain the same data
fi

You would call this script like this:

./myscript file1 file2

after making the script executable with chmod.

share|improve this answer
    
oh, that is nice. Any easy way to get those columns into variables/table? I need to perform extra operations on them before printing output –  SSV Dec 31 '13 at 8:35
    
@SSV OK I updated it –  Robin Green Dec 31 '13 at 9:13
    
well, everything is saved in TAB1 this way. TAB2 is empty (one TAB should contain additional entries, second missing entries). –  SSV Dec 31 '13 at 13:27
    
Partialy solved it by running comm twice - once with -13, and later with -23 –  SSV Dec 31 '13 at 13:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.