cheetsheetz/awk.md

159 lines
2.1 KiB
Markdown

# AWK Cheat Sheet
## Table of Contents
1. [AWK Basics](#awk-basics)
2. [Patterns and Actions](#patterns-and-actions)
3. [Variables](#variables)
4. [Operators](#operators)
5. [Built-in Variables](#built-in-variables)
6. [Control Structures](#control-structures)
7. [Functions](#functions)
8. [Text Processing](#text-processing)
9. [Regular Expressions](#regular-expressions)
10. [Arrays](#arrays)
11. [User-Defined Functions](#user-defined-functions)
12. [Command Execution](#command-execution)
## AWK Basics
### Print Lines
```awk
awk '{print}' filename
```
### Print Specific Column
```awk
awk '{print $2}' filename
```
### Filter with Condition
```awk
awk '$1 > 10 {print}' filename
```
## Patterns and Actions
```awk
# Pattern with Action
pattern1 { action1 }
pattern2 { action2 }
```
## Variables
```awk
# Assigning Variables
variable = value
# Accessing Variables
print variable
```
## Operators
```awk
# Arithmetic Operators
+, -, *, /, %
# Relational Operators
==, !=, >, <, >=, <=
# Logical Operators
&&, ||
```
## Built-in Variables
```awk
# NR: Record Number
NR > 1 {print "Line Number: " NR}
# NF: Number of Fields
{print "Number of Fields: " NF}
```
## Control Structures
```awk
# if Statement
if (condition) {
# Commands
}
# if-else Statement
if (condition) {
# Commands for true condition
} else {
# Commands for false condition
}
```
## Functions
```awk
# Built-in Functions
{
result = sqrt(9)
print "Square Root: " result
}
```
## Text Processing
### Field Separator
```awk
# Change Field Separator
awk -F',' '{print $2}' filename
```
### Output Formatting
```awk
# Formatting Output
awk '{printf "Name: %-10s Age: %d\n", $1, $2}' filename
```
## Regular Expressions
```awk
# Match Pattern
awk '/pattern/ {print}' filename
```
## Arrays
```awk
# Declare an Array
array[1] = "apple"
array[2] = "banana"
# Access Array Element
print array[1]
```
## User-Defined Functions
```awk
# Define a Function
function my_function(parameter) {
# Commands
}
# Call the Function
my_function(value)
```
## Command Execution
```awk
# Execute Command
awk '{cmd = "echo " $1; system(cmd)}' filename
```