Linux awk Command
In Linux, command output and log files often contain more information than you need. The awk command helps you extract specific fields, filter records, and format text directly from the terminal.
It is particularly useful in DevOps when analyzing logs, processing command output, and working with structured text data.
What Is awk?
awk is a text-processing tool that reads input one line at a time and divides each line into fields based on a separator.
For example, consider this record:
Navin Engineering GeneralManager 90000Using awk, you can extract the employee's name, department, designation, or salary without displaying the entire line.
Basic Syntax
awk 'pattern { action }' filename- Pattern: An optional condition that determines which lines to process.
- Action: Specifies what to do with matching lines, such as printing selected fields.
- Filename: The file to process.
awkcan also read input from a pipe.
If no pattern is provided, the action runs for every input line. If no action is provided, matching lines are printed.
Common Built-in Variables
| Variable | Meaning |
|---|---|
$0 | The entire current line |
$1 | The first field |
$2 | The second field |
$3 | The third field |
NR | The current record number across the input |
NF | The number of fields in the current record |
FS | The input field separator |
OFS | The output field separator |
By default, awk separates fields using whitespace, including spaces and tabs.
Sample Data
For the following examples, assume data.txt contains:
Navin Engineering GeneralManager 90000
Akshay Marketing ProductManager 75000
Priya Engineering Developer 65000
Rahul Sales Executive 50000Each line represents an employee, with fields for name, department, designation, and salary.
Printing Data
Print All Lines
awk '{print}' data.txtPrints every line in the file. This is similar to using cat for simple file display.
You can also write:
awk '{print $0}' data.txtHere, $0 represents the entire current line.
Print a Specific Column
To display employee names:
awk '{print $1}' data.txtOutput:
Navin
Akshay
Priya
RahulTo display only employee designations:
awk '{print $3}' data.txtTo display salaries:
awk '{print $4}' data.txtPrint Multiple Columns
You can select multiple fields in the same command.
awk '{print $1, $3}' data.txtOutput:
Navin GeneralManager
Akshay ProductManager
Priya Developer
Rahul ExecutiveBy default, awk separates the printed fields with a space.
Print Custom Text
You can combine fields with custom text to make the output more readable.
awk '{print $1, "is designated as", $3}' data.txtOutput:
Navin is designated as GeneralManager
Akshay is designated as ProductManager
Priya is designated as Developer
Rahul is designated as ExecutiveThis is useful when preparing readable reports from raw text data.
Filtering Data with Patterns
A pattern tells awk which lines to process.
Match a Specific Word
awk '/Engineering/' data.txtOutput:
Navin Engineering GeneralManager 90000
Priya Engineering Developer 65000The expression /Engineering/ matches lines containing that text.
By default, matching is case-sensitive. For example, /Manager/ and /manager/ are different patterns.
Filter Using a Condition
You can compare field values to select specific records.
For example, to display employees with salaries greater than 60000:
awk '$4 > 60000' data.txtOutput:
Navin Engineering GeneralManager 90000
Akshay Marketing ProductManager 75000
Priya Engineering Developer 65000To display only the names of those employees:
awk '$4 > 60000 {print $1}' data.txtOutput:
Navin
Akshay
PriyaThis combines a condition with an action, making awk useful for filtering structured data.
Working with Line Numbers
The built-in variable NR tracks the current record number. For ordinary line-based input, it corresponds to the line number.
Print Lines with Their Numbers
awk '{print NR, $0}' data.txtOutput:
1 Navin Engineering GeneralManager 90000
2 Akshay Marketing ProductManager 75000
3 Priya Engineering Developer 65000
4 Rahul Sales Executive 50000Print Column Values with Line Numbers
awk '{print NR, $1}' data.txtOutput:
1 Navin
2 Akshay
3 Priya
4 RahulThis can help identify specific records when inspecting configuration files or logs.
Adding Headers with BEGIN
The BEGIN block executes before awk processes the input records. It is useful for printing headers or initializing variables.
awk 'BEGIN {print "Name Department"} {print $1, $2}' data.txtOutput:
Name Department
Navin Engineering
Akshay Marketing
Priya Engineering
Rahul SalesHere:
BEGIN { ... }prints the header once before processing the file.{print $1, $2}prints the name and department for each record.
You can also use END to perform an action after all records have been processed.
For example, count the number of records:
awk 'END {print "Total employees:", NR}' data.txtOutput:
Total employees: 4Practical Example: Analyze Logs
Suppose a log file contains space-separated fields and you want to extract the first and third fields:
awk '{print $1, $3}' application.logYou can also combine awk with another command using a pipe.
For example, to extract process IDs and command names from ps output:
ps -ef | awk '{print $2, $8}'This is a simple illustration; the meaning of each field depends on the command's output format.
Important: awk uses whitespace as its default field separator. If your input uses commas, colons, or another delimiter, specify the separator explicitly.
For example, to extract the first and third columns from a comma-separated file:
awk -F ',' '{print $1, $3}' data.csvThe -F option sets the input field separator to a comma.
Quick Reference
| Command | Purpose |
|---|---|
awk '{print}' file | Print all lines |
awk '{print $1}' file | Print the first field |
awk '{print $1, $3}' file | Print the first and third fields |
awk '/pattern/' file | Print lines matching a pattern |
awk '$4 > 60000' file | Print records where the fourth field exceeds 60000 |
awk '{print NR, $0}' file | Print record numbers and complete lines |
awk 'BEGIN {print "Header"} {print $1}' file | Print a header before the data |
awk 'END {print NR}' file | Print the total record count |
awk -F ',' '{print $1}' file.csv | Print the first field from comma-separated data |
Summary
awkprocesses input record by record and splits records into fields.- Use
$1,$2, and$3to access individual fields, and$0to access the entire record. - Use patterns and conditions to filter the data you need.
NRtracks record numbers, whileNFgives the number of fields in the current record.- Use
BEGINfor setup or headers andENDfor summary operations. - Use
-Fwhen the input uses a delimiter other than the default whitespace.
Written By: Muskan Garg
How is this guide?
Last updated on
