Listen to this Post

The `awk` command is a powerful text-processing tool in Linux, enabling users to scan files, match patterns, and perform custom actions on data. Below are practical examples and advanced usage scenarios.
Basic AWK Syntax
awk 'pattern { action }' filename
1. Print Specific Columns
Extract the first and third columns from a file:
awk '{print $1, $3}' data.txt
2. Filter Lines Based on Condition
Print lines where the second column is greater than 100:
awk '$2 > 100 {print $0}' data.txt
3. Use Built-in Variables
– `NR` (Number of Records): Line number
– `NF` (Number of Fields): Number of fields in a line
awk '{print NR, NF, $0}' data.txt
4. Sum a Column
Calculate the sum of the second column:
awk '{sum += $2} END {print sum}' data.txt
5. Conditional Text Replacement
Replace “old” with “new” in the first column only:
awk '$1 == "old" {$1 = "new"} {print}' data.txt
You Should Know: Advanced AWK Techniques
1. Using AWK with Regex
Extract lines containing “error”:
awk '/error/ {print}' logfile.txt
2. Field Separator Customization
Process CSV files (comma-separated):
awk -F ',' '{print $1, $3}' data.csv
3. AWK Script Files
Save AWK commands in a script file (`script.awk`):
BEGIN { print "Processing..." }
{ print $1 }
END { print "Done." }
Run it with:
awk -f script.awk data.txt
4. Multi-Command AWK
Chain multiple commands using `;`:
awk '{if ($1 > 50) print "High"; else print "Low"}' data.txt
5. AWK with System Commands
Execute shell commands from AWK:
awk '{system("echo " $1)}' data.txt
What Undercode Say
The `awk` command is indispensable for Linux users dealing with log parsing, data extraction, and report generation. Combining it with sed, grep, and `cut` enhances its power.
Related Linux Commands to Explore:
– `sed` – Stream editor for text manipulation
– `grep` – Search text using patterns
– `cut` – Extract sections from files
– `sort` – Sort lines of text
– `uniq` – Filter duplicate lines
For further reading, check Advanced AWK Programming.
Expected Output:
1. Sample data processing 2. Filtered logs 3. Calculated sums 4. Formatted reports
(End of article)
References:
Reported By: Xmodulo The – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


