Skip to main content
added explanation
Source Link
αғsнιη
  • 42k
  • 17
  • 75
  • 118

Another awk approach:

awk -F'|' 'NR==FNR{f1[$1FS$2]=$NF;next} {f2[$1FS$2]=$NF} END{for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}; for (y in f2) print y, 0, f2[y] }' file[12] OFS='|' 

###Explanation:

  • NR==FNR{f1[$1FS$2]=$NF;next}, this will run only for file1 and with the key combination of $1FS$2 will store last column value $NF in array called f1 (FS will substitute with | as awk's Field Seperator).
  • {f2[$1FS$2]=$NF}, same as above but this will run only for file2
  • for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}, loop within array f1 and print key (x), its value in file1 f1[x] and if there same file1 key in file2, then print it as well, else print 0 (Used ternary condition f2[x]?f2[x]:0), after that we are also deleting record of same key from file2 with delete f2[x].
  • for (y in f2) print y, 0, f2[y], now array f2 has records which exist in file2 only, so we are printing their key (y), 0 because doesn't not exist in file1 and their value in file2 f2[y].

Another awk approach:

awk -F'|' 'NR==FNR{f1[$1FS$2]=$NF;next} {f2[$1FS$2]=$NF} END{for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}; for (y in f2) print y, 0, f2[y] }' file[12] OFS='|' 

Another awk approach:

awk -F'|' 'NR==FNR{f1[$1FS$2]=$NF;next} {f2[$1FS$2]=$NF} END{for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}; for (y in f2) print y, 0, f2[y] }' file[12] OFS='|' 

###Explanation:

  • NR==FNR{f1[$1FS$2]=$NF;next}, this will run only for file1 and with the key combination of $1FS$2 will store last column value $NF in array called f1 (FS will substitute with | as awk's Field Seperator).
  • {f2[$1FS$2]=$NF}, same as above but this will run only for file2
  • for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}, loop within array f1 and print key (x), its value in file1 f1[x] and if there same file1 key in file2, then print it as well, else print 0 (Used ternary condition f2[x]?f2[x]:0), after that we are also deleting record of same key from file2 with delete f2[x].
  • for (y in f2) print y, 0, f2[y], now array f2 has records which exist in file2 only, so we are printing their key (y), 0 because doesn't not exist in file1 and their value in file2 f2[y].
Source Link
αғsнιη
  • 42k
  • 17
  • 75
  • 118

Another awk approach:

awk -F'|' 'NR==FNR{f1[$1FS$2]=$NF;next} {f2[$1FS$2]=$NF} END{for (x in f1){print x,f1[x],f2[x]?f2[x]:0; delete f2[x]}; for (y in f2) print y, 0, f2[y] }' file[12] OFS='|'