Catalog / AWK Cheatsheet
AWK Cheatsheet
A concise cheat sheet covering essential AWK syntax, patterns, actions, and built-in functions, designed to help you quickly write and understand AWK scripts.
AWK Basics
Syntax
AWK scripts consist of patterns and actions. For each line in the input |
Prints the first field of each line in |
Uses |
|
Patterns
|
Executed before any input is read. |
|
Executed after all input is read. |
|
A boolean expression that determines whether the action is executed. |
|
A range pattern that matches all lines from a line matching |
|
Negates the pattern. The action is executed if the line does not match the pattern. |
Actions
|
|
|
|
|
Variables and Operators
Built-in Variables
|
The entire current line. |
|
The first, second, … field of the current line. |
|
The number of fields in the current line. |
|
The number of the current line. |
|
The name of the current input file. |
|
The field separator (default is whitespace). Can be changed with |
|
The record separator (default is newline). |
|
The output field separator (default is whitespace). |
|
The output record separator (default is newline). |
Operators
|
Assignment operator. |
|
Equality and inequality operators. |
|
Comparison operators. |
|
Regular expression match and non-match operators. |
|
Logical AND, OR, and NOT operators. |
|
Arithmetic operators: addition, subtraction, multiplication, division, exponentiation, modulus. |
|
Increment and decrement operators. |
|
Compound assignment operators. |
User-defined Variables
Variables can be defined and used within AWK scripts. Example:
|
Variables are initialized to zero or the empty string if not explicitly initialized. |
Functions
Built-in Functions
|
Returns the length of the string. |
|
Returns a substring of the string starting at |
|
Returns the starting position of |
|
Splits the string into elements of the |
|
Returns the starting position of the regular expression |
|
Globally substitutes all matches of the regular expression |
|
Converts the string to lowercase. |
|
Converts the string to uppercase. |
|
Formats expressions |
User-Defined Functions
You can define your own functions in AWK. Syntax:
Example:
|
Examples
Simple Examples
Print lines longer than 80 characters: |
Print the total number of fields in the input: |
Print lines containing the word ‘error’: |
Print the last field of each line: |
Advanced Examples
Calculate the average of the values in the first field: |
Print unique lines in a file: |
Sum values in a specific column based on a condition: |