AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

sed Foundations

Addressed stream editing, BRE/ERE distinctions, substitution and escaping, ranges, branching, pattern/hold spaces and bounded multiline examples. No in-place editing, file-write commands, arbitrary scripts or general data parsing.

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, including -n or -E where shown. Export the .sed script and input companion into a new practice folder. /usr/bin/sed is the macOS implementation; no independent version number is advertised, so the evidence pins OS and binary SHA-256. LC_ALL=C limits examples to ASCII byte behavior. Input files are read-only and outputs go to stdout. No -i/-I, w/r commands, executable extensions or arbitrary script interpolation are used. GNU sed behavior and complete POSIX conformance are not claimed. Empty output and exit zero can simply mean no match.

Lessons

The editing cycle

sed is a text-transformation language executed by a stream editor. Ordinarily it reads one line into pattern space, applies commands in order and prints the result. The terminating input newline is handled separately. -n suppresses default printing; p explicitly prints. A successful command can produce no output.

Addresses choose records

A number selects a line, $ selects the last line, and a regex address selects matching pattern spaces. Two addresses select an inclusive range. For a regex second address, matching starts on a later line than the opening match. If the closing marker never arrives, the range continues to end of input.

Regex mode must be explicit

This implementation defaults to basic regular expressions; -E selects extended syntax. Parentheses and + have different roles between modes. These fixed patterns use ASCII and LC_ALL=C. Shell quoting, sed delimiters, regex escapes and replacement escapes are different layers; combining them carelessly changes the program.

Substitution and literal data

s/pattern/replacement/ replaces the first match; g requests all matches. An ampersand in replacement inserts the matched text, and escaped backreferences refer to capture groups. Escape an ampersand to insert it literally. Never build a sed program by concatenating untrusted search or replacement text.

Flow and output

d removes pattern space and starts the next cycle. b branches to a label or the script end; t branches when a substitution has succeeded since the relevant reset. Branches in this pack are forward-only so no unbounded loop is introduced. Duplicated output often means both p and default printing were enabled.

Hold space is separate state

h copies pattern space to hold space, g copies it back, and x exchanges them. G appends a newline and hold space. The fixed-label example keeps only one small value and does not accumulate an entire input file. State persists between cycles within one process.

Multiline work stays bounded

N appends the next input line with an embedded newline. P prints only the first segment while D can restart with remaining segments. This pack demonstrates only fixed two-line combinations, guarded at the last line. A parser for CSV, JSON or nested structured text belongs elsewhere.

Safety and implementation limits

No example edits its input file or uses file-write commands. -n is an output option, not a sandbox: sed scripts can have file side effects on implementations supporting such commands. Error diagnostics are implementation-specific. Resource limits and fresh directories constrain these authored tests, not arbitrary submitted scripts.

Reference cards

Run: sed -f script.sed

Read commands from a fixed script file.

Printing: -n / p

Suppress automatic output; print explicitly.

Address: 2 / $ / /pattern/

Select a line, last line or match.

Range: /BEGIN/,/END/

Inclusive range with stated reopening behavior.

Delete: d

Start a new cycle without this pattern space.

Substitute: s/a/b/ / s/a/b/g

First match or every match.

Matched text: & in replacement

Insert the whole match; escape for a literal &.

BRE group: \(group\) / \1

Capture and reference in default mode.

ERE mode: -E / (group) / +

Extended syntax; pin the invocation.

Command group: address { ... }

Apply a group only to selected pattern spaces.

Copy state: h / g

Copy pattern to hold space or back.

Swap state: x

Exchange pattern and hold space.

Append state: G

Append newline plus hold space.

Next line: N

Append one line with an embedded newline.

Branch: b label / :label

Jump forward in these bounded examples.

Conditional branch: t label

Branch on a successful substitution since reset.

Supporting configuration: Run instructions.txt
Use the exact invocation beside each example, including -n or -E where shown. Export the .sed script and input companion into a new practice folder. /usr/bin/sed is the macOS implementation; no independent version number is advertised, so the evidence pins OS and binary SHA-256. LC_ALL=C limits examples to ASCII byte behavior. Input files are read-only and outputs go to stdout. No -i/-I, w/r commands, executable extensions or arbitrary script interpolation are used. GNU sed behavior and complete POSIX conformance are not claimed. Empty output and exit zero can simply mean no match.

Examples and practice

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

sed 01 - Select lines

-n makes output come only from p. With two input lines, line 2 also satisfies $, so it prints twice; commands are independent.

2p
$p

Expected:

beta
gamma

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -n -f "sed 01 Select lines.sed" < "sed 01 Select lines Input.txt"

Companion file: sed 01 Select lines Input.txt

alpha
beta
gamma

Intentionally invalid sed: expected sed parser diagnostic containing unescaped newline inside substitute pattern. Expected rejection; not a successful program. No runtime execution follows rejection.

s/alpha/beta
sed 02 - Delete addressed lines

Deletion changes only output. A leading-space hash is retained because the comment rule requires # in column one.

/^#/d
/^[[:space:]]*$/d

Expected:

read
code

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 02 Delete addressed lines.sed" < "sed 02 Delete addressed lines Input.txt"

Companion file: sed 02 Delete addressed lines Input.txt

# note
read
  
code
sed 03 - First and global replacement

Commands run in order on the same pattern space. The first substitution changes one blue; the second changes every red.

s/blue/green/
s/red/orange/g

Expected:

green blue orange orange

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 03 First and global replacement.sed" < "sed 03 First and global replacement Input.txt"

Companion file: sed 03 First and global replacement Input.txt

blue blue red red
sed 04 - Matched text and literal ampersand

The first command wraps only the first digit run in brackets using &. The second command inserts a literal ampersand. The pattern and replacement are fixed authored syntax.

s/[0-9][0-9]*/[&]/
s/PLUS/\&/g

Expected:

task [25] & 5

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 04 Matched text and literal ampersand.sed" < "sed 04 Matched text and literal ampersand Input.txt"

Companion file: sed 04 Matched text and literal ampersand Input.txt

task 25 PLUS 5
sed 05 - Basic capture groups

Default BRE uses escaped grouping parentheses. Anchors require the full toy record; unmatched lines pass through unchanged.

s/^\([a-z][a-z]*\):\([0-9][0-9]*\)$/\2 minutes for \1/

Expected:

20 minutes for read
40 minutes for code
invalid

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 05 Basic capture groups.sed" < "sed 05 Basic capture groups Input.txt"

Companion file: sed 05 Basic capture groups Input.txt

read:20
code:40
invalid

Intentionally invalid sed: expected sed parser diagnostic containing unbalanced brackets. Expected rejection; not a successful program. No runtime execution follows rejection.

/[/p
sed 06 - Extended capture groups

-E enables the unescaped parentheses and + syntax used here. The tested replacement backreference syntax remains a backslash plus digit.

s/^([a-z]+):([0-9]+)$/\2 minutes for \1/

Expected:

20 minutes for read
40 minutes for code

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -E -f "sed 06 Extended capture groups.sed" < "sed 06 Extended capture groups Input.txt"

Companion file: sed 06 Extended capture groups Input.txt

read:20
code:40
sed 07 - Inclusive marker range

The matching marker lines are included. -n prevents outside lines from being automatically printed. Missing END keeps the range open to EOF.

/^BEGIN$/,/^END$/p

Expected:

BEGIN
read
END

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -n -f "sed 07 Inclusive marker range.sed" < "sed 07 Inclusive marker range Input.txt"

Companion file: sed 07 Inclusive marker range Input.txt

skip
BEGIN
read
END
skip

Intentionally invalid sed: expected sed parser diagnostic containing undefined label. Expected rejection; not a successful program. No runtime execution follows rejection.

b absent
sed 08 - Remember a fixed label

The first line is copied into hold space and not printed. Each later line appends that label. This holds one bounded label rather than accumulating the stream.

1 {
h
d
}
G
s/\n/ | /

Expected:

read | Study
code | Study

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 08 Remember a fixed label.sed" < "sed 08 Remember a fixed label Input.txt"

Companion file: sed 08 Remember a fixed label Input.txt

Study
read
code
sed 09 - Join two-line groups

N is skipped on the final unpaired line. This pairs records, not quoted CSV rows or arbitrary multiline structures.

$!N
s/\n/ | /

Expected:

read | 20
code | 40

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed 09 Join two-line groups.sed" < "sed 09 Join two-line groups Input.txt"

Companion file: sed 09 Join two-line groups Input.txt

read
20
code
40

Intentionally invalid sed: expected sed parser diagnostic containing extra characters. Expected rejection; not a successful program. No runtime execution follows rejection.

q garbage
sed exercise A - Bounded forward branch

A successful first substitution branches forward to done. Every path reaches the end without looping; the next record starts a fresh cycle.

s/^read$/READ/
t done
s/^code$/CODE/
:done

Expected:

READ
CODE
rest

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed exercise A Bounded forward branch.sed" < "sed exercise A Bounded forward branch Input.txt"

Companion file: sed exercise A Bounded forward branch Input.txt

read
code
rest

Practice: Uppercase exactly read or code, leave other whole lines unchanged, and use a forward branch.

sed exercise B - Trim and select

-n plus the addressed block prints selected lines once. Trimming here follows C-locale whitespace, not a Unicode normalization policy.

s/^[[:space:]]*//
s/[[:space:]]*$//
/^task:/ {
s/^task:[[:space:]]*//
p
}

Expected:

read
code

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -n -f "sed exercise B Trim and select.sed" < "sed exercise B Trim and select Input.txt"

Companion file: sed exercise B Trim and select Input.txt

  task: read  
ignore
	task: code	

Practice: Trim line edges, select lines beginning task:, remove that prefix and print the remaining text once.

sed exercise C - Four observable cases

These are four input/output cases, not four embedded assertions inside sed. The external harness checks exact output. The regex accepts digit strings of any length; it does not enforce the awk pack numeric range.

s/^item=\([0-9][0-9]*\)$/value:\1/

Expected:

value:0
value:120
item=
item=12x

Run with the supplied authored input:

LC_ALL=C /usr/bin/sed -f "sed exercise C Four observable cases.sed" < "sed exercise C Four observable cases Input.txt"

Companion file: sed exercise C Four observable cases Input.txt

item=0
item=120
item=
item=12x

Practice: Rewrite only complete item=<digits> records. Predict zero, multiple digits, empty value 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.