concat two files side-by-side, append difference between fields, and print in tabular format

Viewed 142

Consider I have a two files as below: I need to concatenate and find difference in the new file.

a.txt

a 2019 66
b 2020 50
c 2018 48

b.txt

a 2019 50
b 2019 40
c 2018 45

Desired output:

a 2019 66 a 2019 50 16
b 2020 50 b 2019 40 10
c 2018 48 c 2018 45 3

I tried:

awk -F, -v OFS=" " '{$7=$3-$6}1' file3.txt

it prints

a 2019 66 a 2019 50 0
b 2020 50 b 2019 40 0
c 2018 48 c 2018 45 0

Also can help in printing in tabular format?

2 Answers

Your awk command seems fine except -F,. You should paste those files first.

$ paste a.txt b.txt | awk '{print $0,$3-$6}' | column -t
a  2019  66  a  2019  50  16
b  2020  50  b  2019  40  10
c  2018  48  c  2018  45  3

Within single awk could you please try following.

awk 'FNR==NR{a[FNR]=$0;b[FNR]=$NF;next} {print a[FNR],$0,b[FNR]-$NF}' a.txt b.txt | column -t

Output will be as follows.

a  2019  66  a  2019  50  16
b  2020  50  b  2019  40  10
c  2018  48  c  2018  45  3
Related