0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use awk Command in Linux: Syntax and Examples

The awk command in Linux is a powerful text processing tool that reads input line by line, splits it into fields, and performs actions based on patterns. Use it with the syntax awk 'pattern { action }' filename to filter and manipulate text easily.
📐

Syntax

The basic syntax of the awk command is:

  • awk 'pattern { action }' filename
  • pattern: A condition to match lines (optional).
  • action: Commands to execute on matching lines (optional).
  • filename: The file to process (optional; if omitted, awk reads from standard input).

If no pattern is given, awk applies the action to all lines. If no action is given, it prints the matching lines by default.

bash
awk 'pattern { action }' filename
💻

Example

This example prints the second column of each line from a file named data.txt. It shows how awk splits lines into fields and prints a specific one.

bash
echo -e "apple 10\nbanana 20\ncherry 30" > data.txt
awk '{ print $2 }' data.txt
Output
10 20 30
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to quote the awk program, which can cause shell errors.
  • Using single quotes inside the awk script without escaping.
  • Assuming fields are separated only by spaces; awk treats any whitespace as a separator by default.

Example of wrong and right usage:

bash
awk { print $1 } file.txt  # Wrong: missing quotes
awk '{ print $1 }' file.txt  # Right: quotes included
📊

Quick Reference

CommandDescription
awk '{ print $1 }' filePrint first field of each line
awk '/pattern/ { print $0 }' filePrint lines matching 'pattern'
awk 'NR==3' filePrint the third line
awk '{ print NF }' filePrint number of fields in each line
awk -F, '{ print $2 }' file.csvUse comma as field separator and print second field

Key Takeaways

Use single quotes around the awk program to avoid shell issues.
Fields in awk are accessed with $1, $2, etc., where $0 is the whole line.
Patterns filter which lines the action applies to; omit pattern to process all lines.
Default field separator is whitespace; use -F to specify others like commas.
Test awk commands on small input to understand output before using on big files.