Linux Command - awk
awk is often used to process text files.
Basic Ustage
Syntax
1 | awk 'AWK COMMANDS' [FILE] |
Awk defines variables for you to use. useful for extracting fields from the input
- $0 - the whole line
- $1 - the first field
- $2 - the second field
- $n - the nth field
- $(NF-1) - field count -1
- $NF - field count
- NR - Retrieves total count of processed records
example
1 | echo 'hello awk' | awk '{print $1}' |
output
1 | hello |
You can specify the separator using -F
option. To print the first field in /etc/password:
1 | awk -F ':' '{print $1}' /etc/passwd |
Sample output
1 | root |
To print count, the first and last field of the input field
1 | awk -F ':' '{print NR " - " $1 " - " $(NF) }' /etc/passwd |
Sample output
1 | 1 - root - /bin/bash |
if Statement
1 | awk -F ':' '{if ($1 < "g" ) print $1 }' /etc/passwd |
This will print the names less than “g”
Sample output
1 | daemon |
If else statement
1 | awk -F ':' '{if ($1 < "g" ) print $1; else print "---" }' /etc/passwd |
This will print the names less than “g”, else print “—“
Sample output
1 | --- |
Reference
- Why you should learn just a little Awk by Greg Grothaus
- 30 Examples for Awk Command in Text Processing by Mokhtar Ebrahim