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 -F '[:,]' splits a line on more than one separator

Awk
~/tips/tip-awk-f-regex-separators

echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}'

Splits fields on several different characters at once, using a regular expression as separator.

Config lines and logs don’t always use one separator. Something like host:port,weight has two. awk’s -F takes a regular expression, so you can name both.

echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}'

The brackets mean “any one of these characters”, so the line splits on the colon and on the comma, and this prints web1 8080 5.

A few other patterns that come in handy:

awk -F' *= *' '{print $2}' settings.conf      # key = value, spaces optional
awk -F'\t' '{print $3}' export.tsv             # tabs only
awk -F'[[:space:]]+' '{print $2}' file.txt

The first one is my favorite for config files: it splits on an equals sign with any number of spaces around it, so name=web and name = web both give web.

A difference to keep in mind: the default separator, a single space, is special. It splits on runs of spaces and tabs and ignores them at the start of the line. Any other -F doesn’t: -F'[[:space:]]+' on a line with leading spaces gives an empty first field. And a one-character separator like -F. is taken literally, while longer ones are regular expressions, so -F'..' splits on any two characters.

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 /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' All Awk tips (17) All topics

Link