awk

>Usage

awk (Text Processing and Pattern Scanning Language) is a powerful language used for text processing and pattern scanning. It’s like a Swiss Army knife for text manipulation – you can use it to search, filter, and modify data, often in columns or structured data, making it ideal for analyzing files like logs or CSVs.

>Synopsis

awk [options] 'selection _criteria {action }' input-file > output-file

>Options

-F

-F (field separator): Defines the field separator for splitting the text into columns.

Example 1:

Dots

-zsh

> echo "apple orange banana" | awk -F" " '{print $1}'


apple

$

$ (field reference): Refers to individual fields in the input (e.g., $1, $2).

Example 2:

Dots

-zsh

> echo "apple orange banana" | awk '{print $2}'


orange

NR

NR (Number of Records): Refers to the number of lines processed.

In the example below, NR specifies that only the second line should be processed, and the action prints the first field ($1) of the selected line, where fields are separated by whitespace by default.

Example 3:

Dots

-zsh

> echo -e "apple\norange\nbanana" | awk 'NR == 2 {print $1}'


orange

BEGIN

BEGIN: Executes a set of instructions before processing any input. This is useful for initializing special variables.

Example 4:

Dots

-zsh

> echo -e "apple\norange\nbanana" | awk 'BEGIN {print "Start processing"} {print $1}'


Start processing
apple
orange
banana

END

END: Executes commands after all input is processed.

Example 5:

Dots

-zsh

> echo -e "apple\norange\nbanana" | awk 'END {print "Finished processing"}'


Finished processing

pattern-action

pattern-action: Defines an action to take when a pattern is matched.

Example 6:

Dots

-zsh

> echo -e "apple\norange\nbanana" | awk '/orange/{print "Found orange"}'


Found orange

print

print (default action): Prints the entire line or specified fields.

Example 7:

Dots

-zsh

> echo "apple orange banana" | awk '{print $1, $3}'


apple banana

if-else

if-else: Conditional processing based on patterns or data.

Example 8:

Dots

-zsh

> echo "apple orange" | awk '{if ($1 == "apple") print "It is apple"}'


It is apple

>Quiz

Progress: Question ? out of ?

Question Title

Page written by Andrea Benvegnù