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 :




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


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
  echo $1 and $2 contain the same data

You would call this script like this:

./myscript file1 file2

after making the script executable with chmod.

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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