Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to join two files from the unix command line, inserting zero entries for missing keys

Tags:

join

unix

I'm trying to join two files each of which contains rows of the form <key> <count>. Each file contains a few lines that are missing from the other, and I would like to have zero inserted for all such values rather than omitting these lines (I've seen -a, but this isn't quite what I'm looking for). Is there a simple way to accomplish this?

Here is some sample input:

a.txt

apple 5
banana 7

b.txt

apple 6
cherry 4

expected output:

apple 5 6
banana 7 0
cherry 0 4
like image 456
jonderry Avatar asked Oct 23 '25 05:10

jonderry


1 Answers

join -o 0,1.2,2.2 -e 0 -a1 -a2 a.txt b.txt
  • -o 0,1.2,2.2 → output join field, then 2nd field of 1st file, then 2nd field of 2nd file.
  • -e 0 → Output 0 on empty input fields.
  • -a1 -a2 → Show all values from file 1 and file 2.
like image 52
ninjalj Avatar answered Oct 27 '25 03:10

ninjalj