[awk] Join two files by a shared key

Created on November 30, 2026

Load a lookup table from the first file, then use it while reading the second file. Save these values as names.txt.

1 apple
2 orange

Save the prices as prices.txt.

1 120
2 150

The first column is the shared key.

awk 'NR==FNR {name[$1]=$2; next} {print name[$1], $2}' names.txt prices.txt
apple 120
orange 150

NR counts all records and FNR starts over for each file. Here the first file has records, so NR==FNR identifies it. The lookup loads names by ID, and next skips the rest of the rules for those records. While reading the second file, awk prints each stored name next to the price in column 2.

awk Shell command