4.0 Invoking AWK: Syntax and Command-Line Operations
The strategic importance of AWK lies in its dual-mode execution model, which allows a systems engineer to choose the right tool for the job. Simple, one-off commands can be executed directly from the terminal for rapid log inspection or data filtering, while more complex and reusable logic can be encapsulated in script files, forming a maintainable component in a larger automation pipeline. Understanding both methods is key to leveraging AWK’s full potential.
4.1 Execution Methods
Direct Command-Line Execution
For straightforward tasks, an AWK program can be provided directly on the command line, enclosed in single quotes.
- Syntax: awk ‘[options] ‘program’ file …
The following example uses this method to print the entire contents of the marks.txt file.
[jerry]$ awk ‘{print}’ marks.txt
Using an AWK Program File
For more complex or reusable logic, AWK commands can be saved in a script file. The -f option instructs AWK to read the program from this file instead of the command line.
- Syntax: awk [options] -f program-file file …
First, create a file named command.awk with the desired logic:
File: command.awk
{print}
Next, execute it using the -f option:
[jerry]$ awk -f command.awk marks.txt
This produces the same output as the direct command-line method, demonstrating the interchangeability of the two approaches.
4.2 Essential Command-Line Options
AWK supports a variety of command-line options that modify its behavior. These options allow for variable assignment, debugging, and compatibility control.
| Option | Purpose | Example |
| -v var=val | Assigns a value to a variable before the program begins execution. | awk -v name=Jerry ‘BEGIN{printf “Name = %s\n”, name}’ |
| –dump-variables[=file] | Prints a sorted list of global variables and their final values to a file (default: awkvars.out). | awk –dump-variables ” |
| –lint[=fatal] | Enables checking for non-portable or questionable programming constructs, issuing warnings. | awk –lint ” /bin/ls |
| –profile[=file] | Generates a pretty-printed, profiled version of the program in a file (default: awkprof.out). | awk –profile ‘…’ marks.txt > /dev/null |
| –version | Displays the version information for the AWK implementation. | awk –version |
These command-line tools provide the foundation for leveraging AWK’s core functionality: processing text through the powerful combination of patterns and actions.