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 printf lines up columns into a neat table

Awk
~/tips/tip-awk-printf-columns

printf 'nginx 12.5\npostgres 300\n' | awk '{printf "%-10s %8.1f MB\n", $1, $2}'

Formats output into aligned columns with fixed widths and decimals.

Output that’s split on spaces looks ragged as soon as the values have different lengths. awk’s printf gives every column a fixed width.

printf 'nginx 12.5\npostgres 300\n' | awk '{printf "%-10s %8.1f MB\n", $1, $2}'

This printed:

nginx          12.5 MB
postgres      300.0 MB

%-10s is a text column 10 characters wide, aligned to the left because of the minus. %8.1f is a number 8 characters wide with one decimal, aligned to the right, so the decimal points line up. Unlike print, printf doesn’t add a newline, which is why the \n is there.

I like to add a header in the same format, so the table explains itself:

awk 'BEGIN {printf "%-10s %8s\n", "NAME", "SIZE"} {printf "%-10s %8.1f\n", $1, $2}' sizes.txt

When a value is longer than its width, printf doesn’t cut it off; it pushes the rest of the line to the right. Pick widths for the longest value you expect, or use %-10.10s to truncate text at 10 characters. And as with length, some awks count bytes, so names with accents can end up one column off in mawk.

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