awk Basics
In this page:
Printing a Field
awk automatically splits each line on whitespace into fields numbered $1, $2, and so on, with $0 referring to the entire line. A simple {print $1} program prints just the first field of every input line.
Example: Printing a Field
#!/bin/bash
printf "Alice 30 Engineer\nBob 25 Designer\n" | awk '{print $1}'
Login to try C/C++/Java/PHP code in the editor
Custom Field Separator
-F sets the character (or pattern) used to split fields, which is essential for structured data like CSV where commas separate values instead of whitespace.
Example: Custom Field Separator
#!/bin/bash
echo "alice,30,engineer" | awk -F, '{print $2}'
Login to try C/C++/Java/PHP code in the editor
Using NF and NR
NF holds the number of fields on the current line, and NR holds the current line number (record number) across the whole input, both of which are useful for filtering or validating rows.
Example: Using NF and NR
#!/bin/bash
printf "a b c\nx y\n" | awk '{print "line", NR, "has", NF, "fields"}'
Login to try C/C++/Java/PHP code in the editor
Simple Conditions and Arithmetic
awk programs can include conditions before the action block, so condition { action } only runs the action on matching lines, and awk supports normal arithmetic directly on field values.
Example: Simple Conditions and Arithmetic
#!/bin/bash
printf "apple 3\nbanana 7\ncherry 1\n" | awk '$2 > 2 { print $1, $2 * 10 }'
Login to try C/C++/Java/PHP code in the editor
- Forgetting
$0refers to the whole line, while$1,$2, etc. refer to individual fields. - Assuming fields are always split on a single space; the default field separator is any run of whitespace, and
-Fis needed to change it. - Writing complex logic directly on the command line instead of using
-f script.awkfor anything beyond a one-liner, making quoting a nightmare.
- awk splits each input line into fields, accessible as
$1,$2, ... with$0meaning the whole line andNFthe number of fields. -Fsets the field separator, e.g.-F,for comma-separated data.awk '{print $1}'prints just the first field of every line.NRholds the current line (record) number, which is handy for filtering by position.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: