Exploring awk - Linux Commands
What is the awk Command in Linux?
The awk command in Linux is a versatile and powerful text-processing tool, often used for pattern scanning and data extraction. Named after its creators (Aho, Weinberger, and Kernighan), awk works on files or input streams, scanning each line and applying operations based on specified patterns or conditions. It’s often used in shell scripts for data extraction, transformation, and reporting.
Basic syntax:
awk 'pattern {action}' fileExample:
awk '{print $1}' file.txtOptions
| Option | Description |
|---|---|
| -F | Sets the field separator (default is space or tab) |
| -f | Reads the awk program from a file instead of the command line |
| -v | Allows you to pass in external variables |
Common Use Cases
Printing Specific Columns
One of the most popular awk use cases is extracting columns from a file:
awk '{print $2}' file.txtThis command prints the second column from each line of the file. You can combine columns too:
awk '{print $1, $3}' file.txtFiltering Data with Patterns
You can filter data based on specific conditions, like printing lines that contain a certain word:
awk '/pattern/ {print}' file.txtFor example, to print lines that contain the word “error”:
awk '/error/ {print}' log.txtField Separator
Sometimes your data might be separated by something other than spaces or tabs (like commas in CSV files). You can tell awk to use a different delimiter with the -F option:
awk -F, '{print $1, $2}' data.csvCalculations and Summarization
awk is also useful for simple calculations, such as summing values in a column:
awk '{sum += $3} END {print sum}' file.txtThis command sums all values in the third column of file.txt.
Print Line Numbers
If you want to print lines along with their line numbers, awk can handle that too:
awk '{print NR, $0}' file.txtHere, NR is a built-in variable that represents the current line number, and $0 refers to the entire line.
Additional Help
You can explore more by using the commands:
man awkResources
Getting Started With AWK Command [Beginner’s Guide]
Thank you
Thank you for your time and for reading this!