join

join merges two files on a shared field. For every pair of lines — one from each file — that have the same value in their join field, it prints a combined line. It is the command-line form of a database join.

join [options] file1 file2
$ join employees.txt salaries.txt

If employees.txt has 101 Ada and salaries.txt has 101 80000, join pairs them on the shared 101 and prints 101 Ada 80000.

The input must be sorted #

join works by stepping through both files together, so both files must be sorted on the join field. If they are not, join will miss matches. Sort them first with sort, on the same field join will use.

join checks the ordering as it goes and reports a file that is out of order; --nocheck-order turns that check off, and --check-order forces it on.

Choosing the join field #

By default join joins on the first field of each file, and fields are separated by whitespace.

OptionEffect
-1 FIELDJoin on FIELD of file 1.
-2 FIELDJoin on FIELD of file 2.
-j FIELDJoin on FIELD of both files — shorthand for -1 FIELD -2 FIELD.
-t CHARUse CHAR as the field separator for input and output.

Unmatched lines #

By default join prints only the lines that paired. A line with no match on the other side is dropped. These options bring unmatched lines back:

OptionEffect
-a FILENUMAlso print unpaired lines from file FILENUM (1 or 2).
-v FILENUMPrint only the unpaired lines from file FILENUM, and suppress the joined output.
-e EMPTYFill in any missing field with the string EMPTY.

Shaping the output #

OptionEffect
-o FORMATBuild each output line from the field list FORMAT, rather than the default layout.
-i, --ignore-caseIgnore letter case when comparing join fields.
--headerTreat the first line of each file as column headers — print them, paired, without trying to match them.
-z, --zero-terminatedTreat the NUL character as the line delimiter.

Exit status #

CodeMeaning
0Success.
1A file could not be read, was not sorted, or an option was invalid.

Edit this page