KKAIROS
Practical guideIllustrative3 min read

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.

Published:

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.txt

Command:

awk '{print NF}' f.txt; awk -F, '{print NF}' f.txt

Recorded output:

3
1

TE-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:

6

Exit 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 string

Exit 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.

Ad

Source

Source: https://www.gnu.org/software/gawk/manual/

Evidence

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