Skip to main content
This guide demonstrates how to combine the power of awk with Bash to process delimited text files. We’ll compare a pure awk script to a Bash/awk hybrid, then progressively build a reusable salary‐benchmarking tool.

Why Bash-AWK Hybrids?

  • Pure awk scripts are concise for text processing.
  • Embedding awk inside Bash adds flexibility (variables, flags, CLI args).
  • Shebangs (#!/usr/bin/env …) let you run scripts directly.

Pure awk Script (salary.awk)

Bash Script Embedding awk (print_names.sh)

You can run either script by:
Or invoke awk directly:

Preparing the Data Source

Our employees.txt file uses | as the field separator and contains:
The image shows a text file named "employees.txt" containing a list of employees with details such as name, department, job title, email, and salary.
Set the field separator with -F or FS to split on |.

Salary Thresholds


1. Basic One-Liner

Print first name, last name, and salary for every employee:
Output:

2. Filter by Salary Range

Use -v to pass thresholds into awk:
This shows both high and low earners in one stream.

3. Add a Header with BEGIN

Introduce a one-time header via BEGIN:

4. Wrap into a Bash Script (salary.sh)

For readability and reuse, move the awk call into a Bash script:
Make it executable and run:

5. Separate “Up” and “Down” Sections (salary-v2.sh)

Print distinct headers for high and low salaries:

6. One Header per Group (salary-v3.sh)

Use flags inside awk to avoid repeating headers:

7. Parameterize with CLI Arguments (salary-v4.sh)

Allow users to override thresholds when running the script:
Run with defaults:
Or specify custom thresholds:

Next Steps

You’ve now explored:
  • Pure awk vs Bash/awk hybrids
  • Using -v to pass variables into awk
  • Conditional headers with BEGIN and internal flags
  • Parameterizing scripts via CLI
Practice customizing these scripts for different file formats, field counts, or more complex filtering logic.

References

Watch Video

Practice Lab