Overview
The `print` statement in `awk` is used to send extracted data from input records (lines) to standard output. You can select data by field (column), combine multiple fields for output, and control output based on conditions. `print` is one of the most fundamental actions in `awk` scripting.
Key Features
The key features of `awk print` are as follows:
- Outputting entire lines or specific fields
- Utilizing built-in variables (NR, NF, FS, RS, etc.)
- Combining strings and fields for output
- Supporting conditional output
- Adding a newline after each output by default
Usage Examples
Various examples using the `print` statement in `awk`. Assume the example file `data.txt` contains: `apple 10 red banana 20 yellow orange 15 orange`
Outputting Entire Lines
awk '{print}' data.txt
Prints all lines of the input file as they are.
Outputting the First Field
awk '{print $1}' data.txt
Prints only the first field ($1) of each line.
Combining Multiple Fields and Strings
awk '{print "Item:", $1, "Color:", $3}' data.txt
Prints the first and third fields separated by a comma, and adds a custom string.
Outputting When a Specific Condition is Met
awk '$2 > 15 {print}' data.txt
Prints the entire line only if the second field ($2) is greater than 15.
Outputting the Last Field
awk '{print $NF}' data.txt
Prints only the last field ($NF) of each line. NF is a built-in variable representing the total number of fields in the current line.
Outputting After Changing the Field Separator
echo "fruit,100,red\nbanana,200,yellow" | awk -F',' '{print $1, $2}'
Specifies the input field separator (-F) as a comma (,) and prints the first and second fields. (Example file: `fruit,100,red\nbanana,200,yellow`)
Tips & Precautions
Tips and points to note for more effective use of `awk print`.
Performance and Usage Tips
- Use `printf` instead of `print`: `printf` allows for precise control of formatting, similar to C's `printf`. `print` by default inserts OFS (Output Field Separator) between each argument and adds OSR (Output Record Separator, default newline), whereas `printf` requires the user to specify the format.
- Clearly specify the field separator (`-F`): If the input file's field separator is not a space, use the `-F` option to ensure accurate field separation.
- Manage complex logic in `awk` script files: For longer scripts, managing them in separate files using `awk -f script.awk data.txt` is recommended for readability and maintainability.
- Utilize built-in variables: Using `awk`'s powerful built-in variables such as `NR` (current record number), `NF` (number of fields in the current record), `FS` (input field separator), and `RS` (input record separator) enables more flexible processing.