BSD Awk Cheatsheet
#
BSD Awk is the implementation of awk
used in BSD systems, often with a more limited feature set compared to GNU Awk.
Basic Syntax
#
Command/Option | Example | Description |
---|
awk '{print $1}' file.txt | awk '{print $1}' data.txt | Print the first field of each line from the file |
awk '/pattern/' file.txt | awk '/error/' log.txt | Print lines that match the pattern |
awk '{print $1, $3}' file.txt | awk '{print $1, $3}' data.txt | Print the first and third fields from each line |
awk -F, '{print $1}' file.csv | awk -F, '{print $1}' data.csv | Print the first field from a comma-separated file |
Field Separators
#
Command/Option | Example | Description |
---|
awk -F ' ' '{print $1}' file.txt | awk -F ' ' '{print $1}' data.txt | Set space as the field separator |
awk -F ':' '{print $1}' file.txt | awk -F ':' '{print $1}' passwd.txt | Set colon as the field separator |
Patterns and Actions
#
Command/Option | Example | Description |
---|
awk '$3 > 50' file.txt | awk '$3 > 50' data.txt | Print lines where the third field is greater than 50 |
awk '{sum += $2} END {print sum}' file.txt | awk '{sum += $2} END {print sum}' sales.txt | Sum the values in the second field and print the total |
awk 'BEGIN {FS=","; OFS="\t"} {print $1, $2}' file.csv | awk 'BEGIN {FS=","; OFS="\t"} {print $1, $2}' data.csv | Set input field separator to comma and output field separator to tab |
Built-in Variables
#
Command/Option | Example | Description |
---|
awk 'NR==1 {print $0}' file.txt | awk 'NR==1 {print $0}' data.txt | Print the first line of the file (NR is the record number) |
awk 'END {print NR}' file.txt | awk 'END {print NR}' data.txt | Print the number of lines in the file |
This cheatsheet provides essential BSD Awk commands for text processing and data extraction.