Awk
Awk
The Awk command is a powerful tool used for text processing in Unix and
Linux systems. It allows users to search for patterns in files, manipulate
data, and generate reports. With its versatile functionality, Awk is
commonly used for tasks such as extracting specific columns from a file,
performing mathematical operations, and automating repetitive tasks. Its
simple syntax and powerful capabilities make it a favorite among system
administrators and programmers alike.
1. [-F ifs]: This option sets the field separator (FS) used by AWK to
split input lines into fields. Here:
3. [-v var=val]: This option allows you to declare a variable (var) and
assign it a value (val) that can be accessed within the AWK program.
For example, -v myvar=10 would declare a variable myvar with the value
10 in AWK.
4. [argument]: This represents the input data or file(s) that AWK will
process. If no input is specified, AWK reads from standard input
(usually what is piped or redirected into it).
Exemple;
grades.txt
Alice 85
Bob 72
Charlie 90
David 68
Eve 95
bash
output
Alice
Charlie
Eve
$1 → first field
$2 → second field
awk -F " " '$1 == "Alice" { print $1 " has " $2 }' grades.txt
Alice has 85
pattern1 { action1 }
pattern2 { action2 }
pattern3 { action3 }
...
Patterns
Actions
Actions specify what AWK should do when a pattern is true. Actions can
include:
Commands: print statements, variable assignments, arithmetic
operations, etc.
Control statements: if, else, for, while, etc., for more complex logic.
NF: represents the number of fields (or columns) in the current input
line.
$NF: represents the value of the last field (or column) in the current
input line.
NF would be 4 (since there are four fields: Alice, 25, 30, 35).
Directly provide the AWK program as a string argument to the awk command.
Example:
```bash
Write your AWK program in a separate file and execute it using the -f
option with awk.
Example:
```awk
# print_second_field.awk
{ print $2 }
```bash
Pipe input directly into the awk command using echo or other commands.
Example:
```bash
Example:
```bash
Hello
World
END
awk '{print "hello king ! "}'