join Command on Linux: Merge Two Sorted Files by Key Column

join command linux - custom-join-featured.png

join on Linux is the relational-database-style merge for flat files — both inputs must be sorted on the join field. When IDs in one file need labels from another, join beats manual VLOOKUP-style scripts.

See: paste,
sort,
cut.

Prepare sorted files

Each file sorted on the join column — often column 1.

bashprep
sort -t, -k1,1 ids.csv > ids.sorted
sort -t, -k1,1 names.csv > names.sorted
sort
join field

Basic join

Default whitespace delimiter; field 1 on both sides.

bashjoin
join ids.sorted names.sorted
join
default

Custom delimiter

-t sets separator; -1 and -2 pick key columns.

bashcsv keys
join -t, -1 1 -2 1 ids.sorted names.sorted
-t,
keys

Unpaired lines

-a prints lines without a match on that file (outer join style).

TipIf join returns empty output, the usual bug is unsorted input — verify with sort -c or re-sort explicitly.
join -a
outer

Quick Reference

  • Sort both files on key
  • join file1 file2 or join -t, f1 f2
  • Unmatched: join -a1 -a2

Related tutorials

Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.