AWK is a powerful text-processing tool in Linux and Unix. It is used for pattern scanning and processing. Below are some commonly used awk
commands with practical examples.
1. What is AWK?
- AWK is a scripting language designed for text processing and pattern matching.
- It processes structured data such as CSV, logs, and space/tab-separated files.
- AWK reads a file line by line, splits each line into fields, and applies specified operations.
2. Basic Syntax
The basic syntax of an awk
command is:
pattern
– Specifies when to apply the action.action
– Specifies what to do (print, calculate, modify, etc.).filename
– The input file.
3. Print a File’s Content
- This prints every line of
employees.txt
, similar tocat employees.txt
.
4. Print Specific Columns
$1
,$2
,$3
, etc., represent columns (fields).- Example (
employees.txt
file): - Output:
5. Print Lines Matching a Pattern
- Finds and prints lines containing “Alice”.
6. Print Lines Based on a Condition
- Prints employees with a salary greater than 5000.
- Output:
7. Count the Number of Lines
NR
(Number of Records) holds the count of processed lines.- Output:
8. Calculate Sum of a Column
- Adds up all values in the third column.
- Output:
9. Use a Custom Field Separator
For a CSV file (employees.csv
):
Use -F
to define the field separator:
- Output:
10. Print Only Even Rows
- Prints only even-numbered lines.
11. Find Maximum Salary
- Finds the highest salary.
12. AWK with Piping
- Displays filenames and their sizes.
13. Replace a Column Value
- Replaces the second column with “David”.
1. Print Specific Columns from a File
Command:
Explanation:
Prints the first and third columns of file.txt
.
Example:
2. Print Lines Matching a Pattern
Command:
Explanation:
Prints lines containing the word “Alice”.
Example Output:
3. Print Lines with a Condition (Salary > 5000)
Command:
Explanation:
Prints employees with salaries greater than 5000. Example Output:
4. Print the Sum of a Column
Command:
Explanation:
Calculates and prints the sum of salaries.
Example Output:
5. Count the Number of Lines
Command:
Explanation:
Prints the total number of lines in the file.
Example Output:
6. Use Field Separator (CSV File)
Command:
Explanation:
Uses a comma ,
as the field separator.
Example (employees.csv
):
Output:
7. Replace a Column Value
Command:
Explanation:
Replaces the second column with “David”.
8. Print Only Even Rows
Command:
Explanation:
Prints only even-numbered lines.
9. Find the Maximum Salary
Command:
Explanation:
Finds the highest salary in the third column.
10. AWK in a Pipeline
Command:
Explanation:
Lists file names and their sizes.
These are just some basic examples. AWK is very powerful for text processing, and you can use it to manipulate, filter, and analyze text files efficiently.