lab.awk.im

awk one-liners I actually use

· awk, shell

Given the domain name, this had to be the first post. No clever tricks, just the ones that show up in my shell history every week.

Columns

# sum the 3rd column
awk '{s += $3} END {print s}' file

# last field of every line
awk '{print $NF}' file

# regular users from /etc/passwd
awk -F: '$3 >= 1000 {print $1}' /etc/passwd

Lines

# dedupe, keep the first occurrence, keep order (no sort needed)
awk '!seen[$0]++' file

# everything between two markers, inclusive
awk '/^BEGIN/,/^END/' file

# join lines with commas
awk 'NR > 1 {printf ","} {printf "%s", $0} END {print ""}' file

Logs

# top client IPs in an access log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head

# requests per status code (combined log format, status is field 9)
awk '{c[$9]++} END {for (k in c) print k, c[k]}' access.log

System

# filesystems above 80%
df -P | awk 'NR > 1 && $5+0 > 80 {print $6, $5}'

# listening TCP sockets, address only
ss -tlnH | awk '{print $4}'

# memory used by a process name, in MB
ps -C caddy -o rss= | awk '{s += $1} END {printf "%.1f MB\n", s/1024}'

$5+0 forces a numeric comparison: "85%"+0 is 85. That one took me longer than I would like to admit.