brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: awk 'NR==FNR' looks up values from a second file

Awk
~/tips/tip-awk-nr-fnr-join

awk -F, 'NR==FNR {name[$1]=$2; next} FNR>1 {print $1, ($2 in name ? name[$2] : "unknown"), $3}' names.csv orders.csv

Joins two files on a shared column, like a small database lookup, in one awk command.

One file has ids and names, another has orders with only the id. Putting the name next to each order is a join, and awk does it without a database.

awk -F, 'NR==FNR {name[$1]=$2; next} FNR>1 {print $1, ($2 in name ? name[$2] : "unknown"), $3}' names.csv orders.csv

NR counts lines over all files together and FNR restarts at 1 for every file. They’re only equal while awk reads the first file. In that part, the line’s name goes into an array under its id, and next skips the rest of the program. For the second file the first block no longer runs, so every order gets its name looked up. FNR>1 skips the header row.

With ids 1 and 2 in names.csv and an order for id 3, the output is:

A anna 10
B bob 5
C anna 7
D unknown 1

The ($2 in name ? ... : "unknown") part is there on purpose. Without it, a missing id prints an empty field, which I think is easy to miss.

One trap: if the first file is empty, NR==FNR is also true for the whole second file, and everything ends up in the lookup array. When the lookup file might be empty, test FILENAME == ARGV[1] instead. Also, the first file is kept in memory, so put the smaller one first.

Further reading: GNU awk manual, POSIX awk specification

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' awk -F, 'NR>1 {print > ($2".csv")}' data.csv echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' All Awk tips (17) All topics

Link