0

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

asked Dec 31, 2013 at 7:41

1 Answer 1

0

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.

answered Dec 31, 2013 at 8:18
4
  • 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 Commented Dec 31, 2013 at 8:35
  • @SSV OK I updated it Commented Dec 31, 2013 at 9:13
  • well, everything is saved in TAB1 this way. TAB2 is empty (one TAB should contain additional entries, second missing entries). Commented Dec 31, 2013 at 13:27
  • Partialy solved it by running comm twice - once with -13, and later with -23 Commented Dec 31, 2013 at 13:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.