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.
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.txtCommand:
sed 's/aa/bb/' f.txt; sed 's/aa/bb/g' f.txtRecorded output:
bb aa
bb bbTE-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]cExit 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.txtCommand:
sed 's/a/b' f.txtRecorded output: none, standard output was empty.
Standard error from the same run:
sed: -e expression #1, char 5: unterminated `s' commandExit 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.
Source
Evidence
TE-24-A: sed s/// replaces the first match per line unless g is used
- 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-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