1

I have 2 (dummy) files

file1.txt

Tom 25
John 27
Bob 22
Justin 37
Nick 19
Max 42

file2.txt

Tom 25
John 40
Bob 22
Justin 37
Nick 19
Max 24

I want to compare the Second field of these files (the numbers). Then If they are different, report using the First field (Names). So the expected output would be the following.

John's age in file1.txt is different from file2.txt
Max's age in file1.txt is different from file2.txt

I don't know if my approach is good but I first parse the ages into another file and compare them. If they are different, I will look in which line number is the difference. Then I will go back to the original file and parse the Name of the person from THAT line.

I run the following code in shell.

$  awk '{print $2}' file1.txt > tmp1.txt
$  awk '{print $2}' file2.txt > tmp2.txt
$
$  different=$(diff tmp1.txt tmp2.txt | awk '{$1=""; print $0')
$
$  if ["${different}"]; then
$     #This is to get the line number where the ages are different
$     #so that I can go to THAT line in file1.txt and get the first field.
$     awk 'NR==FNR{a[$0];next}!($0 in a){print FNR}' tmp1.txt tmp2.txt > lineNumber.txt
$  fi

However, I am blocked here. I don't know if my approach is right or there's an easier approach.

Thanks a lot

4

3 回答 3

4
awk 'NR==FNR{a[$1]=$2;next} $2!=a[$1]{print "Age of "$1" is different"}' file1 file2
于 2013-11-01T20:46:39.777 回答
1

如果两个文件都列出了相同的名称,则如下所示:

join file{1,2}.txt | awk '$2 != $3 { print "Age of " $1 " is different" }'
于 2013-11-01T20:37:29.483 回答
1
awk '
    NR==FNR{a[$1]=$2;next}
    a[$1] != $2 {print $1"\047s age in "ARGV[1]" is different from "ARGV[2]}
' file1.txt file2.txt
于 2013-11-01T20:31:24.230 回答