KKAIROS
Practical guideIllustrative2 min read

sed basics: replace text in a stream

sed edits a stream using a pattern space; s/old/new/ replaces the first match on each line, and the g flag replaces all matches.

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-24-A: sed s/// replaces the first match per line unless g is used

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'aa aa\n' > f.txt

Command:

sed 's/aa/bb/' f.txt; sed 's/aa/bb/g' f.txt

Recorded output:

bb aa
bb bb

TE-24-B: in a sed replacement, & stands for the text that matched

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

printf 'abc\n' | sed 's/b/[&]/'

Recorded output:

a[b]c

Exit status: 0. This status and the output match what was written before the run. This is the status of sed, the last command in the pipe.

TE-24-C: expected non-zero exit: a substitution without its closing slash is rejected

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'a\n' > f.txt

Command:

sed 's/a/b' f.txt

Recorded output: none, standard output was empty.

Standard error from the same run:

sed: -e expression #1, char 5: unterminated `s' command

Exit status: 1. This status and the output match what was written before the run.

TE-24-B: the pattern s/b/[&]/ turned abc into a[b]c, so & stood for the matched b. TE-24-C: the substitution s/a/b has no closing slash. sed exited with status 1 and printed sed: -e expression #1, char 5: unterminated `s' command to standard error.

Limits

-i syntax differs between GNU and BSD; sed is not only per-line editing.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-24-A | sed s/// replaces the first match per line unless g is used | 0 | PASS | 0b86fa40760f | | TE-24-B | in a sed replacement, & stands for the text that matched | 0 | PASS | bee06e999995 | | TE-24-C | expected non-zero exit: a substitution without its closing slash is rejected | 1 | PASS | c0212a211967 |

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