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 '{print $NF}' prints the last column, however many there are

Awk
~/tips/tip-awk-nf-last-field

echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}'

Grabs the last field of each line, even when lines have a different number of fields.

When lines have a different number of columns, $3 or $5 points at something else on every line. The last column is easier to reach.

NF is the number of fields on the current line, so $NF is the last one. That makes it great for paths:

echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}'

That prints access.log nginx: the file name and the folder it’s in. $(NF-1) needs the parentheses. Without them, $NF-1 means “the last field minus one” as a number, and for text that’s -1.

It shines on command output where the interesting part sits at the end, like the mount point in df or the file name in ls -l, which can contain spaces and break a fixed column number. Well, almost: with spaces in a name, $NF only gets the last word. For file names with spaces, a tool that prints the name alone, like find -printf '%f\n', is the better choice in my view.

Watch out for empty lines. There NF is 0, and $0 is the whole (empty) line, so you get blank output rather than an error. Add NF as a condition, NF {print $NF}, to skip them.

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