[Bash] awk command

Zhentiw發表於2024-05-17

The awk command is a powerful text processing tool used for pattern scanning and processing.

// exammple.txt
Hello World
This is a sample file
Bash scripting is powerful
Learning grep, awk, and sed
Another line with the word World
awk '{print $1}' example.txt

Hello
This
Bash
Learning
Another

This command prints the first field (column) of each line.

awk '{print $1, $2}' filename.csv`

Hello World
This is
Bash scripting
Learning grep,
Another line

awk '{print $1 " is " $2 " years old."}' data.txt

Other actions:

Actions in awk:
Printing:
print: Print the specified fields or text.
Example: awk '{print $1, $2}' filename.txt

Pattern Matching:
if (condition) {action}: Execute actions based on conditions.
Example: awk '{if ($2 > 30) print $1}' filename.txt

Arithmetic Operations:
Perform calculations on fields.
Example: awk '{sum = $2 + $3; print sum}' filename.txt

String Operations:
Concatenate strings, change case, and more.
Example: awk '{print toupper($1)}' filename.txt

Built-in Variables:
NR: Current record number.
NF: Number of fields in the current record.
Example: awk '{print NR, NF}' filename.txt

User-defined Variables:
Define and use your own variables.
Example: awk '{x = $2 * 2; print x}' filename.txt

Loops:
for, while: Perform actions in a loop.
Example: awk '{for (i = 1; i <= NF; i++) print $i}' filename.txt

Arrays:
Define and use arrays.
Example: awk '{arr[$1] = $2} END {for (i in arr) print i, arr[i]}' filename.txt

Practice:

echo -e "Name Age Score\nAlice 30 85\nBob 25 90\nCharlie 35 95" > data.txt

$ awk '{print $0}' data.txt
Name Age Score
Alice 30 85
Bob 25 90
Charlie 35 95

# Use awk to print lines where the age is greater than 30:
$ awk '{if ($2 > 30) print $0}' data.txt
Name Age Score
Charlie 35 95

# Calculate the sum of the age and score for each person and print it:
$ awk '{sum = $2 + $3; print $1, sum}' data.txt
Name 0
Alice 115
Bob 115
Charlie 130

# Convert the name to uppercase and print it:
$ awk '{print toupper($1)}' data.txt
NAME
ALICE
BOB
CHARLIE

# Print the record number and number of fields for each line:
$ awk '{print NR, NF}' data.txt
1 3
2 3
3 3
4 3

# Double the age and print it:
$ awk '{x = $2 * 2; print $1, x}' data.txt
Name 0
Alice 60
Bob 50
Charlie 70

# Print each field of every record:
$ awk '{for (i = 1; i <= NF; i++) print $i}' data.txt
Name
Age
Score
Alice
30
85
Bob
25
90
Charlie
35
95

# Store the age in an array indexed by the name and print the array at the end:
$ awk '{arr[$1] = $2} END {for (i in arr) print i, arr[i]}' data.txt
Bob 25
Alice 30
Charlie 35
Name Age

awk '{print "Name: " $1 ", Score: " $3}' data.txt
Name: Name, Score: Score
Name: Alice, Score: 85
Name: Bob, Score: 90
Name: Charlie, Score: 95

相關文章