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
1 Answer 1
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.
-
oh, that is nice. Any easy way to get those columns into variables/table? I need to perform extra operations on them before printing outputSSV– SSV2013年12月31日 08:35:45 +00:00Commented Dec 31, 2013 at 8:35
-
@SSV OK I updated itRobin Green– Robin Green2013年12月31日 09:13:29 +00:00Commented 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).SSV– SSV2013年12月31日 13:27:08 +00:00Commented Dec 31, 2013 at 13:27
-
Partialy solved it by running comm twice - once with -13, and later with -23SSV– SSV2013年12月31日 13:54:27 +00:00Commented Dec 31, 2013 at 13:54