printf Formatting

Left-aligned string, right-aligned number
cat <<'EOF' > /tmp/demo.txt
nginx 4821
postgres 1337
redis 982
haproxy 27014
EOF
awk '{printf "%-20s %10d\n", $1, $2}' /tmp/demo.txt
Fixed decimal places
printf '3.14159\n2.71828\n1.41421\n' | awk '{printf "%.2f\n", $1}'
Leading zeros — zero-padded integers
printf '42\n7\n256\n1\n1023\n' | awk '{printf "%05d\n", $1}'
Hex output
printf '255\n4096\n65535\n16\n' | awk '{printf "%x\n", $1}'
Multi-column table with borders
cat <<'EOF' > /tmp/demo.txt
nginx 4821 98.30
postgres 1337 72.15
redis 982 45.60
haproxy 27014 99.97
EOF
awk '{printf "| %-15s | %8d | %6.2f%% |\n", $1, $2, $3}' /tmp/demo.txt
Formatted process listing from ps
ps aux --sort=-%cpu | awk 'NR<=11 {printf "%-10s %6s %5s%% %5s%% %s\n", $1, $2, $3, $4, $11}'
Pad PIDs with leading zeros
ps aux | awk 'NR>1 {printf "PID:%06d CMD:%s\n", $2, $11}' | head -10
Right-aligned numeric table with header
cat <<'EOF' > /tmp/stats.txt
web-proxy-01 87.3 62.1
db-primary 34.8 91.4
cache-redis 12.5 28.7
app-node-03 99.1 78.3
EOF
awk 'BEGIN{printf "%-15s %10s %10s\n", "HOST", "CPU%", "MEM%"; printf "%-15s %10s %10s\n", "----", "----", "----"} {printf "%-15s %10.1f %10.1f\n", $1, $2, $3}' /tmp/stats.txt