0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use awk in Bash: Simple Guide and Examples

Use awk in bash to process and analyze text by specifying patterns and actions. The basic syntax is awk 'pattern { action }' filename, where awk reads input line by line and performs actions on matching lines.
📐

Syntax

The basic syntax of awk in bash is:

  • awk 'pattern { action }' filename
  • pattern is a condition to match lines (optional).
  • action is what to do with matching lines, like printing fields.
  • filename is the input file or data source.

If no pattern is given, awk applies the action to all lines.

bash
awk 'pattern { action }' filename
💻

Example

This example prints the second column of a file named data.txt where the first column equals "apple".

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

Common Pitfalls

Common mistakes when using awk in bash include:

  • Not quoting the awk program, causing shell errors.
  • Using single quotes inside single quotes without escaping.
  • Confusing field separators; by default, fields are split by whitespace.
  • Forgetting to specify the input file or pipe data correctly.

Always quote the awk script and use double quotes inside single quotes carefully.

bash
echo "apple 10" | awk $1 == "apple" { print $2 }

# Correct way:
echo "apple 10" | awk '$1 == "apple" { print $2 }'
Output
awk: cmd. line:1: $1 == "apple" { print $2 } awk: cmd. line:1: ^ syntax error 10
📊

Quick Reference

CommandDescription
awk '{ print $1 }' filePrint first field of each line
awk '$2 > 10' filePrint lines where second field is greater than 10
awk -F, '{ print $1 }' file.csvUse comma as field separator
awk 'NR == 1' filePrint only the first line
awk '{ print NR, $0 }' filePrint line number and line

Key Takeaways

Always quote your awk script to avoid shell parsing errors.
Use $1, $2, etc., to refer to fields in each line.
Patterns filter which lines to process; actions define what to do.
Field separator defaults to whitespace but can be changed with -F.
Test your awk commands on sample data to understand output.