AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

awk Foundations

Pattern/action processing, records and fields, validated numeric input, associative arrays, deterministic order, functions and reports. No CSV parser, GNU awk extensions, process execution or arbitrary file access.

Audience: Learners comfortable saving plain text and invoking an installed command-line tool.

Practice: 4 to 6 hours.

Runtime and boundaries: Use the exact invocation beside each example. Export its .awk script and input companion into a new practice folder; LC_ALL=C pins byte-oriented ASCII behavior. /usr/bin/awk --version reports 20200816. Current upstream awk has features absent here; no --csv, GNU awk sorting functions or whole-POSIX conformance is claimed. All programs write stdout only. The browser exports text and never executes it. Do not interpolate untrusted text into an awk program; -v values also interpret backslash escapes and are not a raw-byte transport. Only fixed authored scripts and bounded toy inputs are tested.

Lessons

Patterns and actions

awk is a text-processing language evaluated by the installed awk program. For each input record, matching rules run in source order. A missing pattern matches every record; a missing action prints the record. BEGIN runs before records and END runs afterward. These examples use explicit actions to make output predictable.

Records, fields and separators

With the default settings, newline separates records and FS=" " collapses runs of whitespace into fields. $0 is the whole record; $1 is the first field, NF the field count and NR the record count. A literal colon separator does not implement CSV quoting. Assigning a field can rebuild $0 using OFS.

Strings are not validated numbers

Arithmetic can convert strings and accept numeric prefixes, so coercion alone is not validation. The contract example checks one to three ASCII digits, then a value in 0..120. Values like 001 are accepted; signs, decimals and blanks are rejected. Totals are limited to at most 100 accepted records. Surrounding field whitespace is accepted; a blank record is rejected.

Arrays and report order

Associative arrays map string keys to values. for (key in array) does not guarantee report order. Store first-seen keys in a separate numbered array or use a fixed explicit order. The membership operator in distinguishes an absent key from a stored zero; avoid reading a missing element when testing existence.

Text matching and replacement

awk patterns use extended regular expressions. Anchors express whole-record or whole-field rules. index searches literal text; a string used as a dynamic regular expression has pattern semantics. sub and gsub mutate the selected text and return replacement counts. Replacement ampersands and backslashes have special meaning.

Functions and local names

Scalar parameters are passed by value; array parameters refer to the caller array. Names not declared as parameters are global. Extra trailing parameters can serve as local variables when omitted at the call. Keep the input contract explicit and avoid accidental shared global state.

Flow, exit and END

next skips remaining rules for this record. exit stops normal input processing, but END still runs. An error flag prevents END from printing a success report after rejection. A numeric exit status is separate from stdout. There is no claimed syntax-only sandbox: only fixed parser-failure fixtures are exercised.

Scope and safe practice

LC_ALL=C makes these ASCII and byte-level demonstrations reproducible; Unicode grapheme processing is outside this pack. Empty input is tested. No getline, system, pipes, output-file redirection, environment access or untrusted script generation is used. A temporary directory and test timeout are not an arbitrary-code sandbox.

Reference cards

Rule: pattern { action }

Run matching actions in source order.

Lifecycle: BEGIN / END

Before records and after input processing.

Record: $0 / NR

Whole current record and overall ordinal.

Fields: $1 / NF

First field and number of fields.

Separators: FS / OFS / ORS

Input fields, output fields and output records.

Output: print / printf

Use a fixed printf format for data.

Patterns: ~ / !~ / ^ / $

Regex matching, negation and anchors.

Literal search: index(text, needle)

Return one-based position or zero.

Slice: substr(text, start, count)

One-based text slice.

Replacement: sub / gsub

First or all substitutions; returns count.

Map: totals[key]

Associative array access.

Presence: key in totals

Check membership without fetching a value.

Function: function f(x, local) {...}

Extra omitted parameters can be local names.

Skip: next

Continue with the next record.

Stop: exit 2

Stop input; END still runs.

Contract: regex then numeric range

Validate shape before numeric conversion.

Supporting configuration: Run instructions.txt
Use the exact invocation beside each example. Export its .awk script and input companion into a new practice folder; LC_ALL=C pins byte-oriented ASCII behavior. /usr/bin/awk --version reports 20200816. Current upstream awk has features absent here; no --csv, GNU awk sorting functions or whole-POSIX conformance is claimed. All programs write stdout only. The browser exports text and never executes it. Do not interpolate untrusted text into an awk program; -v values also interpret backslash escapes and are not a raw-byte transport. Only fixed authored scripts and bounded toy inputs are tested.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

awk 01 - Records and fields

Default whitespace fields collapse spaces and tabs; the sample has exactly two fields per record.

{ printf "row=%d fields=%d first=%s last=%s\n", NR, NF, $1, $NF }

Expected:

row=1 fields=2 first=read last=20
row=2 fields=2 first=code last=40

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 01 Records and fields.awk" < "awk 01 Records and fields Input.txt"

Companion file: awk 01 Records and fields Input.txt

read 20
code 40

Intentionally invalid awk: expected awk parser diagnostic containing syntax error. Expected rejection; not a successful program. No runtime execution follows rejection.

BEGIN { print ( }
awk 02 - Match and select

The rule tests field count and a literal field value. It selects text rather than assuming the second field is numeric.

NF == 2 && $1 == "read" { print $2 }

Expected:

20
15

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 02 Match and select.awk" < "awk 02 Match and select Input.txt"

Companion file: awk 02 Match and select Input.txt

read 20
code 40
read 15
awk 03 - Field reconstruction

Assigning $1 rebuilds the record using OFS. A colon-delimited toy record has no quoting or escaping grammar; it is not CSV.

BEGIN { FS = ":"; OFS = " | " }
NF == 2 { $1 = toupper($1); print $0 }

Expected:

READ | 20
CODE | 40

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 03 Field reconstruction.awk" < "awk 03 Field reconstruction Input.txt"

Companion file: awk 03 Field reconstruction Input.txt

read:20
code:40
awk 04 - Validate before summing

All records must satisfy the bounded numeric contract. END still runs after exit, so failed suppresses a misleading total. Failure output is on stdout by this explicit toy contract.

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
{
    if (NF != 1 || !valid($1) || NR > 100) {
        print "rejected"; failed = 1; exit 2
    }
    total += $1
}
END { if (!failed) printf "Total: %d\n", total }

Expected:

Total: 60

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 04 Validate before summing.awk" < "awk 04 Validate before summing Input.txt"

Companion file: awk 04 Validate before summing Input.txt

20
40

Intentionally invalid awk: expected awk parser diagnostic containing non-terminated string. Expected rejection; not a successful program. No runtime execution follows rejection.

BEGIN { x = "unfinished
awk 05 - First-seen report order

The authored input is one nonempty word per record. Report order follows first occurrence, independent of associative-array iteration.

{
    if (!($1 in count)) order[++size] = $1
    count[$1]++
}
END {
    for (i = 1; i <= size; i++)
        printf "%s: %d\n", order[i], count[order[i]]
}

Expected:

read: 2
code: 1
rest: 1

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 05 First-seen report order.awk" < "awk 05 First-seen report order Input.txt"

Companion file: awk 05 First-seen report order Input.txt

read
code
read
rest
awk 06 - Missing versus zero

Membership is independent of the stored value. This does not fetch count["code"], which could create a missing element.

BEGIN {
    count["read"] = 0
    print "read present:", ("read" in count)
    print "code present:", ("code" in count)
    print "read value:", count["read"]
}

Expected:

read present: 1
code present: 0
read value: 0

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 06 Missing versus zero.awk" < /dev/null
awk 07 - Literal search and replacement

index treats the dot literally. gsub uses a fixed regex and literal replacement text; arbitrary replacement escaping is outside this script.

{
    text = $0
    changes = gsub(/blue/, "green", text)
    printf "%d | %d | %s\n", index($0, "."), changes, text
}

Expected:

5 | 2 | green.green
0 | 0 | red

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 07 Literal search and replacement.awk" < "awk 07 Literal search and replacement Input.txt"

Companion file: awk 07 Literal search and replacement Input.txt

blue.blue
red

Intentionally invalid awk: expected awk parser diagnostic containing nonterminated character class. Expected rejection; not a successful program. No runtime execution follows rejection.

/[/ { print }
awk 08 - Function local state

The omitted trailing prefix parameter is local to this call; it does not modify the global prefix. Scalar arguments are passed by value.

function label(text, prefix) {
    prefix = "item"
    return prefix ": " text
}
BEGIN {
    prefix = "outer"
    print label("read")
    print prefix
}

Expected:

item: read
outer

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 08 Function local state.awk" < /dev/null

Intentionally invalid awk: expected awk parser diagnostic containing syntax error. Expected rejection; not a successful program. No runtime execution follows rejection.

function broken( { return 1 }
awk 09 - Skip and finish

Only a hash at the beginning marks a comment; a whitespace-only record has NF zero. This exact convention is deliberate.

/^#/ { next }
NF == 0 { next }
{ kept++ }
END { printf "Kept: %d\n", kept }

Expected:

Kept: 2

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk 09 Skip and finish.awk" < "awk 09 Skip and finish Input.txt"

Companion file: awk 09 Skip and finish Input.txt

# note
read

code
awk exercise A - Bounded mean

The count guard prevents division by zero. Accepted inputs contain at most ten bounded values; formatting follows LC_ALL=C.

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
{
    if (NF != 1 || !valid($1) || NR > 10) {
        print "rejected"; failed = 1; exit 2
    }
    sum += $1; count++
}
END {
    if (!failed && count) printf "Mean: %.1f\n", sum / count
    else if (!failed) print "Mean: none"
}

Expected:

Mean: 20.0

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk exercise A Bounded mean.awk" < "awk exercise A Bounded mean Input.txt"

Companion file: awk exercise A Bounded mean Input.txt

10
20
30

Practice: Compute a mean for one to ten values in 0..120, report none for empty input, and reject malformed records.

awk exercise B - Stable unique lines

The entire line is the key. Blank lines are valid data here and appear once; order follows input. The corpus is tiny, so unbounded memory growth is not addressed.

!($0 in seen) { seen[$0] = 1; print $0 }

Expected:

read
code
rest

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk exercise B Stable unique lines.awk" < "awk exercise B Stable unique lines Input.txt"

Companion file: awk exercise B Stable unique lines Input.txt

read
code
read
rest

Practice: Print each distinct whole line once, preserving its first occurrence.

awk exercise C - Observable assertions

The four checks run inside BEGIN. A mismatch exits nonzero before the final success line. This is a small observable test example, not a complete framework.

function valid(s) {
    return s ~ /^[0-9]+$/ && length(s) <= 3 && (s + 0) <= 120
}
function check(actual, expected) {
    if (actual != expected) { print "test failed"; exit 1 }
    passed++
}
BEGIN {
    check(valid("0"), 1)
    check(valid("120"), 1)
    check(valid("121"), 0)
    check(valid("12x"), 0)
    printf "Assertions: %d passed\n", passed
}

Expected:

Assertions: 4 passed

Run with the supplied authored input:

LC_ALL=C /usr/bin/awk -f "awk exercise C Observable assertions.awk" < /dev/null

Practice: Write checks for zero, upper bound, out-of-range input and numeric-prefix text.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a text transform
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Provide the fixed script, separate input file, exact invocation, output and locale assumptions. Separate predicted behavior from executed evidence.
Debug a reproducible stream
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Reduce the input and distinguish parser errors, no matches, wrong output and process failure. Separate predicted behavior from executed evidence.
Test boundaries and semantics
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Include empty input, missing fields, literal punctuation, malformed records and ordering; specify exit status. Separate predicted behavior from executed evidence.
Refactor without changing output
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve bytes, line order, range behavior and failure policy; show regression cases. Separate predicted behavior from executed evidence.
Document the input contract
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. State record layout, delimiters, numeric limits, escaping layers, locale, side effects and implementation scope. Separate predicted behavior from executed evidence.
Explain with an exercise
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Walk through one record or editing cycle, predict the result and offer a separate exercise solution. Separate predicted behavior from executed evidence.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.