tips
17 tips Awk
One command, setting or habit at a time about Awk: what it does, the line to copy and a caveat or two.
Text processing 17
-
Replaces all matches of a pattern in the line or in one chosen column, and counts them.
echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' -
Writes each line to a file named after a value in that line, such as a country code.
awk -F, 'NR>1 {print > ($2".csv")}' data.csv -
Extracts part of a string by start position and length, counting from 1.
echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' -
Shows how awk turns decimals into whole numbers, and why 2.5 can become 2.
echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' -
Splits fields on several different characters at once, using a regular expression as separator.
echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' -
Grabs the last field of each line, even when lines have a different number of fields.
echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' -
Lists every line above a certain length with file name and line number.
awk 'length > 120 {print FILENAME ":" FNR ": " length}' *.py -
Formats output into aligned columns with fixed widths and decimals.
printf 'nginx 12.5\npostgres 300\n' | awk '{printf "%-10s %8.1f MB\n", $1, $2}' -
Treats each paragraph as one record, so you can filter whole blocks instead of single lines.
awk 'BEGIN {RS=""} /[email protected]/' contacts.txt -
Joins two files on a shared column, like a small database lookup, in one awk command.
awk -F, 'NR==FNR {name[$1]=$2; next} FNR>1 {print $1, ($2 in name ? name[$2] : "unknown"), $3}' names.csv orders.csv -
Drops every line that has no visible content, also lines with just spaces or tabs.
awk NF file.txt > clean.txt -
Totals a number column separately for each value in another column, like a GROUP BY.
awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csv -
Rebuilds every line with a new field separator, for turning aligned output into CSV.
printf 'a b c\n' | awk -v OFS=, '{print}' # a b c -
Reads the header row once and then selects columns by name instead of by number.
awk -F, 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col["amount"]}' orders.csv -
Prints a block of lines from one matching line up to and including another.
awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' bundle.pem -
Adds up all the numbers in one column of a file or command output.
awk -F, '{s+=$2} END {print s}' costs.csv -
Removes duplicate lines from a file and keeps the original order of the rest.
awk '!seen[$0]++' list.txt > unique.txt
Nothing in this filter yet.