awk commands

15 commands, each with a one-line explanation. Click a command to copy it, or its title for details.

Commands 15 shown

  • awk '{print $3}' file.txt

    Print the 3rd whitespace-delimited field

    linux

  • awk -F: '{print $1, $3}' /etc/passwd

    Use colon as field separator, print user and UID

    linux

  • awk '/ERROR/ {print NR": "$0}' app.log

    Print line number and content for lines matching ERROR

    linux · debug

  • awk '{sum += $4} END {print sum}' access.log

    Accumulate a numeric column and print total

    linux

  • awk '/START/,/END/' file.txt

    Range pattern: include lines from START to END inclusive

    linux

  • awk 'NR>1 {print $1, $2}' data.csv

    Process all lines except the first (header)

    linux

  • awk '{count[$1]++} END {for (k in count) print count[k], k}' access.log | sort -rn

    Frequency count of the first field (e.g. IP addresses)

    linux · network

  • awk '{print $NF}' file.txt

    NF holds the number of fields; $NF is the last field

    linux

  • awk '$2 > 500 && $5 == "POST"' access.log

    Print lines where field 2 > 500 AND field 5 is POST

    linux

  • awk '{printf "%-20s %5d\n", $1, $2}' data.txt

    Aligned printf formatting with fixed column widths

    linux

  • awk -f transform.awk input.txt

    Load awk program from an external script file

    linux

  • awk '{gsub(/foo/, "bar"); print}' input.txt > tmp && mv tmp input.txt

    Global substitution and write back to same file

    linux

  • gawk -v FPAT='([^,]+)|("[^"]+")' '{print $2}' data.csv

    Parse quoted CSV fields correctly with FPAT in gawk

    linux

  • awk 'BEGIN{print "Start"} {lines++} END{print lines" lines processed"}' file.txt

    Run code before and after processing all lines

    linux

  • awk 'NR==FNR{a[$1]=$2; next} $1 in a {print $0, a[$1]}' lookup.txt data.txt

    Left-join data.txt with lookup.txt on first field

    linux