awk command in Linux: field processing

Updated November 1, 2026

The awk command splits each line into fields and processes them by a 'condition { action }' rule.

Syntax

awk 'condition { action }' file

Common cases

awk '{ print $1 }' access.log        # the first field of each line
awk '{ print $1, $4 }' access.log    # the first and fourth
awk '$4==404 { n++ } END { print n }' access.log   # count by a condition
awk -F: '{ print $1 }' /etc/passwd   # -F: a colon field separator

Sample output

$ awk '{ print $3 }' app.log | head -3
INFO
INFO
DEBUG
$ awk '$3=="ERROR" { n++ } END { print n }' app.log
3
$ awk -F: '{ print $1, $3 }' /etc/passwd | head -3
root 0
daemon 1
bin 2

How it works: fields, $0 and END

awk splits each line into fields by whitespace: $1 is the first field, $2 the second, $0 the whole line, NF the number of fields. A program is a set of 'condition { action }' rules: for each line awk tests the condition and, if true, runs the action. The special blocks BEGIN { } and END { } fire before and after all lines - END is where you print the final total. Use -F to change the field separator.

Common mistakes

Keep the awk program in single quotes. In double quotes the shell substitutes $1 before awk even starts, usually with an empty string, so what reaches awk from awk "{ print $1 }" is { print }, and it prints whole lines. Nothing fails, the result is just wrong.

print $3 $4 and print $3, $4 do different things. Without the comma awk glues the fields together: INFOserver. With the comma it puts OFS between them, a space by default: INFO server.

A log message is not one field. awk cuts the line 2026-07-19 09:12:04 INFO server started on port 8080 on spaces, so $4 gives back only server and the rest lands in $5, $6 and on. To get the tail of the line, loop from the field you need up to NF, or take the whole line as $0.

Used in

You need this in the lesson Text: grep, sed, awk. The theory is the chapter Bash in depth.

See also

The grep command, The sed command, Regular expressions.

Try it

Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.