awk basics: split records into fields
awk reads records and splits them into fields, then runs a pattern-action program. Tested here: awk's default field separator splits on runs of whitespace.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-40-A: awk's default field separator splits on runs of whitespace
Setup for this run, inside a throwaway directory (mktemp -d):
printf 'a b\tc\n' > f.txtCommand:
awk '{print NF}' f.txt; awk -F, '{print NF}' f.txtRecorded output:
3
1TE-40-B: awk can add up a field over all lines and print the total in an END block
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
printf '1 2\n3 4\n' | awk '{s+=$2} END {print s}'Recorded output:
6Exit status: 0. This status and the output match what was written before the run. This is the status of awk, the last command in the pipe.
TE-40-C: expected non-zero exit: an awk program with an unclosed brace is a syntax error
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
awk '{print'Recorded output: none, standard output was empty.
Standard error from the same run:
awk: cmd. line:1: {print
awk: cmd. line:1: ^ unexpected newline or end of stringExit status: 1. This status and the output match what was written before the run.
TE-40-B: the second field of the two lines is 2 and 4, and the END block printed their sum, 6. TE-40-C: awk '{print' exited with status 1. Standard error holds lines that start with awk: cmd. line:1: and the last one ends with unexpected newline or end of string.
Limits
Default splitting is on runs of whitespace, not a single space; RS can change records.
Source
Source: https://www.gnu.org/software/gawk/manual/
Evidence
TE-40-A: awk's default field separator splits on runs of whitespace
- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-40-A | awk's default field separator splits on runs of whitespace | 0 | PASS | e051f45610c5 | | TE-40-B | awk can add up a field over all lines and print the total in an END block | 0 | PASS | 615a287fb226 | | TE-40-C | expected non-zero exit: an awk program with an unclosed brace is a syntax error | 1 | PASS | 190218056ef0 |
Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides