cheetsheetz/awk.md

167 lines
2.2 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
### Pattern with Action
```awk
pattern1 { action1 }
```
```awk
pattern2 { action2 }
```
## Variables
### Assigning Variables
```awk
variable = value
```
### Accessing Variables
```awk
print variable
```
## Operators
### Arithmetic Operators
```awk
+, -, *, /, %
```
### Relational Operators
```awk
==, !=, >, <, >=, <=
```
### Logical Operators
```awk
&&, ||
```
## Built-in Variables
### NR: Record Number
```awk
NR > 1 {print "Line Number: " NR}
```
### NF: Number of Fields
```awk
{print "Number of Fields: " NF}
```
## Control Structures
### if Statement
```awk
if (condition) {
# Commands
}
```
### if-else Statement
```awk
if (condition) {
# Commands for true condition
} else {
# Commands for false condition
}
```
## Functions
### Built-in Functions
```awk
{
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
### Match Pattern
```awk
awk '/pattern/ {print}' filename
```
## Arrays
### Declare an Array
```awk
array[1] = "apple"
array[2] = "banana"
```
### Access Array Element
```awk
print array[1]
```
## User-Defined Functions
### Define a Function
```awk
function my_function(parameter) {
# Commands
}
```
### Call the Function
```awk
my_function(value)
```
## Command Execution
### Execute Command
```awk
awk '{cmd = "echo " $1; system(cmd)}' filename
```