awk

GNU Awk Cheatsheet #

GNU Awk (gawk) is the GNU implementation of the awk programming language, providing additional features beyond the POSIX standard.

Basic Syntax #

Command/OptionExampleDescription
gawk '{print $1}' file.txtgawk '{print $1}' data.txtPrint the first field of each line from the file
gawk '/pattern/' file.txtgawk '/error/' log.txtPrint lines that match the pattern
gawk '{print $1, $3}' file.txtgawk '{print $1, $3}' data.txtPrint the first and third fields from each line
gawk -F, '{print $1}' file.csvgawk -F, '{print $1}' data.csvPrint the first field from a comma-separated file

Field Separators #

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

Patterns and Actions #

Command/OptionExampleDescription
gawk '$3 > 50' file.txtgawk '$3 > 50' data.txtPrint lines where the third field is greater than 50
gawk '{sum += $2} END {print sum}' file.txtgawk '{sum += $2} END {print sum}' sales.txtSum the values in the second field and print the total
gawk 'BEGIN {FS=","; OFS="\t"} {print $1, $2}' file.csvgawk '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
gawk 'NR==1 {print $0}' file.txtgawk 'NR==1 {print $0}' data.txtPrint the first line of the file (NR is the record number)
gawk 'END {print NR}' file.txtgawk 'END {print NR}' data.txtPrint the number of lines in the file

Extensions and Features #

Command/OptionExampleDescription
gawk --lint script.awkgawk --lint process.awkEnable warnings about deprecated features
gawk --versiongawk --versionDisplay the version of GNU Awk

This cheatsheet provides essential GNU Awk (gawk) 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.