-1

I have two files which have data in a format like this:

cat File1.txt

A: 1
B: 2
C: 3
D: 4
E: 5

cat File2.txt

A: 10
B: 2
C: 30
D: 4
F: 6

I was wondering how I could print the diff for common keys like:

A: 1, 10
C: 3, 30
user2517676
  • 969
  • 6
  • 15
  • 25
  • 1
    How much do you know about awk? Click the [tag:awk] tag above, then click the [Learn more...](https://stackoverflow.com/tags/awk/info) link for a brief primer. Have you made any attempts to solve this yourself? – glenn jackman Jan 18 '21 at 21:02

3 Answers3

0

You could try

awk -F":" 'NR==FNR{a[$1]=$2} FNR!=NR && a[$1] && a[$1]!=$2{print $1":"a[$1]","$2}' File1.txt File2.txt
F. Knorr
  • 3,045
  • 15
  • 22
0

As it seems there are no duplicates in the file, this should do:

$ awk '{if(($1 in a)&&$2!=a[$1])print $1,a[$1] ", " $2;else a[$1]=$2}' file1 file2

Output:

A: 1, 10
C: 3, 30

Explained:

$ awk '{
    if(($1 in a) && $2!=a[$1])    # if $1 already seen and $2 not equal to previous
        print $1,a[$1] ", " $2    # output
    else 
        a[$1]=$2                  # else store the value as seen for the first time
}' file1 file2
James Brown
  • 36,089
  • 7
  • 43
  • 59
0
$ cat tst.awk
BEGIN { OFS=", " }
NR==FNR {
    a[$1] = $2
    next
}
($1 in a) && (a[$1] != $2) {
    print $0, a[$1]
}

$ awk -f tst.awk file2 file1
A: 1, 10
C: 3, 30
Ed Morton
  • 188,023
  • 17
  • 78
  • 185