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 can pick a CSV column by its header name

Awk
~/tips/tip-awk-column-by-header-name

awk -F, 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col["amount"]}' orders.csv

Reads the header row once and then selects columns by name instead of by number.

Column numbers break as soon as someone adds a column to an export. Reading the header once and selecting by name is sturdier.

awk -F, 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col["amount"]}' orders.csv

On the first line, the loop stores the position of every header name in an array, so col["amount"] becomes 3 for the example file. next skips the header itself. On every other line, $col["amount"] is the field in that position. When the export gets an extra column at the front, the command still finds the right one.

With a variable you get a small reusable tool:

awk -F, -v want=email 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col[want]}' users.csv

I’d check the header for surprises. Exports from Windows tools often end in a carriage return, so the last header is really "amount\r" and the lookup finds nothing. gawk and mawk then print the whole line, because an empty index means $0, and macOS awk stops with an error. Strip the \r first with tr -d '\r'. A BOM at the start of the file does the same to the first header. And quoted fields with commas still need a real CSV tool.

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