Use BEGIN/END blocks

Run code before and after all lines are processed

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

tool
awk15 commands
tags
awklinux

More awk commands

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

    Join data.txt with lookup.txt on the first field; lines without a match are skipped

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

    Print the 3rd field, split by whitespace

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

    Use a colon as the separator and print the user name and UID

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

    Print the line number and text of lines with ERROR

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

    Add up a numeric column (here the 4th) and print the total

all 15 awk commands