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 split one file into several, named after a column

Awk
~/tips/tip-awk-print-redirect-split-file

awk -F, 'NR>1 {print > ($2".csv")}' data.csv

Writes each line to a file named after a value in that line, such as a country code.

Splitting a big CSV by country, customer or status sounds like a job for a script. awk does it in one line, because print can redirect to a file whose name it builds from the data.

awk -F, 'NR>1 {print > ($2".csv")}' data.csv

With rows like ann,nl,3 and bob,de,5, this creates nl.csv and de.csv. awk opens each file the first time it needs it and keeps it open, so every later line for that value is appended.

That one-liner skips the header line. To put the header into every new file instead:

awk -F, 'NR==1 {h=$0; next} !($2 in seen) {print h > ($2".csv"); seen[$2]=1} {print >> ($2".csv")}' data.csv

On a small file with a header, nl.csv ends up with the header plus its two matching rows.

The caveats: the first > empties an existing file of that name, so run it in a clean folder. And awks keep every file open, so a column with thousands of distinct values can hit the open-file limit. Call close() on files you are done with, or sort the input first.

Further reading: GNU awk manual: string functions

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' 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}' echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' All Awk tips (17) All topics

Link