awk

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/OptionExampleDescription
awk '{print $1}' file.txtawk '{print $1}' data.txtPrint the first field of each line from the file
awk '/pattern/' file.txtawk '/error/' log.txtPrint lines that match the pattern
awk '{print $1, $3}' file.txtawk '{print $1, $3}' data.txtPrint the first and third fields from each line
awk -F, '{print $1}' file.csvawk -F, '{print $1}' data.csvPrint the first field from a comma-separated file

Field Separators #

Command/OptionExampleDescription
awk -F ' ' '{print $1}' file.txtawk -F ' ' '{print $1}' data.txtSet space as the field separator
awk -F ':' '{print $1}' file.txtawk -F ':' '{print $1}' passwd.txtSet colon as the field separator

Patterns and Actions #

Command/OptionExampleDescription
awk '$3 > 50' file.txtawk '$3 > 50' data.txtPrint lines where the third field is greater than 50
awk '{sum += $2} END {print sum}' file.txtawk '{sum += $2} END {print sum}' sales.txtSum the values in the second field and print the total
awk 'BEGIN {FS=","; OFS="\t"} {print $1, $2}' file.csvawk 'BEGIN {FS=","; OFS="\t"} {print $1, $2}' data.csvSet input field separator to comma and output field separator to tab

Built-in Variables #

Command/OptionExampleDescription
awk 'NR==1 {print $0}' file.txtawk 'NR==1 {print $0}' data.txtPrint the first line of the file (NR is the record number)
awk 'END {print NR}' file.txtawk 'END {print NR}' data.txtPrint the number of lines in the file

This cheatsheet provides essential BSD Awk commands for text processing and data extraction.

awk

Explore our comprehensive cheatsheets to enhance your knowledge and efficiency. Each cheatsheet provides detailed command options, examples, and descriptions to help you master various tools and technologies.