sed: Stream Editing Line by Line

sed: Stream Editing Line by Line in Bash: --- Picture a busy shoe-repair shop. Along one wall, a conveyor brings customers' shoes in from the intake counter,…


The Analogy: The Cobbler's Repair Bench and Job Ticket

Picture a busy shoe-repair shop. Along one wall, a conveyor brings customers' shoes in from the intake counter, one shoe at a time. The cobbler lifts each shoe onto the bench, works on it, and sets it on the finished rack behind them before reaching for the next. Only ever one shoe sits on the bench at a moment: the bench is a single-item workspace, and the shop's whole throughput is just this one motion repeated for every shoe that comes down the line. Nothing is done to a shoe until it is on the bench, and once it leaves the bench the cobbler does not touch it again.

Clipped to the bench is a job ticket -- a short, ordered list of standing instructions that applies to every shoe unless a line on the ticket says otherwise. "Re-dye any scuff mark. Re-stitch a loose seam. If it is a boot, replace the lace." The cobbler runs down the ticket top to bottom for the shoe currently on the bench, then sends it to the rack and brings up the next one. The ticket is written once and obeyed the same way for thousands of shoes; the cobbler is not improvising per shoe, they are applying a fixed script to a stream of items.

Two details make the bench powerful. First, an instruction can be restricted to certain shoes: "only the third pair", "only shoes stamped with a size over ten", "only boots". An instruction with no such restriction applies to every shoe. Second, there is a small side shelf next to the bench where the cobbler can park a shoe mid-job -- to hold one member of a pair while finishing its partner, then bring it back. Most jobs never touch the side shelf, but it is there when a task needs to remember something between shoes.

The bench has one genuine hazard. Normally the cobbler works from the conveyor and puts finished shoes on the rack, so the customer's original is never at risk until the work is deliberately handed back. But some shops, to save space, work on the customer's only pair with no spare and no photograph of the original. If the job ticket is wrong -- dyes the wrong panel, cuts the wrong seam -- the original is ruined and there is nothing to restore it from. The safe habit is to keep the original on the conveyor and produce a corrected copy on the rack, committing to overwrite the customer's pair only once you have seen the corrected copy is right. That is exactly the difference between letting sed stream to your screen and letting it edit a file in place.


Syntax or Core Structure

sed -- the stream editor -- reads its input one line at a time, applies a script of editing commands to each line in turn, and writes the result to standard output. By default the original file is never changed: sed is a filter, like the cobbler working from the conveyor to the rack. The single most common command is s, substitute, which replaces text matching a pattern:

# prices.txt
apple:red:30
banana:yellow:12
grape:green:45
lemon:yellow:20
sed 's/yellow/gold/' prices.txt

Output:

apple:red:30
banana:gold:12
grape:green:45
lemon:gold:20

The command s/yellow/gold/ means "find yellow and replace it with gold". sed places each line on its workbench (called the pattern space), runs the script against it, and by default prints the result. Note two things: lines with no match, like the apple and grape rows, pass through untouched, and the substitution replaced only the first yellow on each line, because s without a flag stops after the first match. The file prices.txt on disk is unchanged; only the stream printed to the terminal carries the edit.


Technical Depth: Addresses, Flags and Back-References

The substitute command and its flags

The s command takes flags after the closing delimiter that change how it behaves. The most important is g (global), which replaces every match on the line rather than just the first. Compare the two on a line full of dots:

# dots.txt contains: a.b.c.d
sed 's/\./-/' dots.txt      # first match only
sed 's/\./-/g' dots.txt     # every match

Output:

a-b.c.d
a-b-c-d

The dot is escaped as \. because an unescaped . in a sed pattern matches any character, exactly as in grep. These are the flags you will reach for most often:

FlagEffect
gReplace all matches on the line, not just the first
IMatch case-insensitively (GNU sed)
pPrint the line if a substitution was made
3Replace only the third match on the line

Selecting lines: addresses

By default a command runs on every line. An address placed before the command restricts it to certain lines, matching the job ticket's "only boots" clause. An address can be a line number, the special $ for the last line, a /regex/ match, or a start,end range. The d (delete) and p (print) commands make addresses easy to see; p is usually paired with -n, which switches off the automatic printing so only explicitly printed lines appear:

sed -n '2p' prices.txt        # print only line 2
sed '2d' prices.txt           # delete line 2, print the rest
sed -n '/yellow/p' prices.txt # print only lines matching yellow
sed '/green/d' prices.txt     # delete lines matching green

Output:

banana:yellow:12
apple:red:30
grape:green:45
lemon:yellow:20
banana:yellow:12
lemon:yellow:20
apple:red:30
banana:yellow:12
lemon:yellow:20

The four commands print in sequence: line 2 alone; then the file with line 2 removed; then the two yellow lines; then the file with the green line removed. This table summarises the address forms:

AddressSelects
5Line number 5 only
$The last line of the input
/regex/Every line matching the regex
2,4Lines 2 through 4 inclusive
/a/,/b/From the first line matching a to the next matching b

Capture groups and back-references

Substitution becomes reformatting when the pattern captures parts of the line in groups and the replacement refers back to them. With -E for extended regular expressions, (...) captures and \1, \2, \3 recall the captured pieces in order. This turns the colon-separated records into a readable report:

sed -E 's/^([a-z]+):([a-z]+):([0-9]+)$/\1 = \3 (\2)/' prices.txt

Output:

apple = 30 (red)
banana = 12 (yellow)
grape = 45 (green)
lemon = 20 (yellow)

Group 1 is the name, group 2 the colour, group 3 the price; the replacement reorders them as name = price (colour). A special token & in the replacement stands for the entire matched text, useful for wrapping something rather than reordering it, for example s/[0-9]+/[&]/ puts brackets around every number.

Chaining edits and the side shelf

A single sed invocation can carry several commands. Separate them with ; or give each its own -e flag, and they run in order on every line, just as the cobbler works down the whole job ticket before releasing a shoe:

sed -e 's/yellow/gold/' -e 's/red/crimson/' prices.txt

Output:

apple:crimson:30
banana:gold:12
grape:green:45
lemon:gold:20

Beyond the pattern space, sed keeps a second buffer called the hold space -- the side shelf where a line can be parked and recalled. It is rarely needed, but it is what lets sed remember something between lines. The classic demonstration reverses a file's line order, the job tac does, by appending each line to a growing stash and printing it only at the end:

# seq.txt contains: one / two / three
sed '1!G;h;$!d' seq.txt

Output:

three
two
one

If that one-liner looks cryptic, that is the point: once an edit needs the hold space it is usually clearer to reach for awk or a small script. The hold space is worth knowing exists, not worth forcing every job through.

Editing files in place

Everything so far streamed to the screen and left the file alone. The -i flag makes sed write its edits back into the file. Used carelessly this is the shop that works on the customer's only pair; used with a suffix it keeps a backup of the original first:

sed -i.bak 's/yellow/gold/g' prices.txt

Output:

This prints nothing, because the output went into the file. Afterwards prices.txt holds the edited text and prices.txt.bak holds the untouched original. The habit worth building is to run the command without -i first, read the result on screen, and only add -i.bak once the output is exactly what you want.


Real World Example: Redacting Tokens from a Shared Log

A support engineer needs to attach an application log to a public ticket, but the log lines contain bearer tokens that must never leave the building. Each line has the shape ... token=VALUE ..., and the value is a run of upper-case letters and digits. This mask_log.sh streams the log and replaces every token value with the word REDACTED, leaving everything else intact.

# app.log
2026-01-05 login user=alice token=AKIA1234567890 ok
2026-01-05 fetch user=bob token=AKIA0987654321 ok
2026-01-05 error user=carol token=AKIAABCDEFGHIJ fail
#!/usr/bin/env bash
# mask_log.sh -- redact bearer tokens before sharing a log
set -euo pipefail

FILE="${1:-app.log}"
sed -E 's/(token=)[A-Z0-9]+/\1REDACTED/' "$FILE"

Running bash mask_log.sh prints:

Output:

2026-01-05 login user=alice token=REDACTED ok
2026-01-05 fetch user=bob token=REDACTED ok
2026-01-05 error user=carol token=REDACTED fail

The pattern captures the literal token= in group 1, then matches the value with [A-Z0-9]+. The replacement \1REDACTED writes the captured token= back and follows it with the masking word, so the key stays and only the secret is removed. Because sed streams to standard output, the original app.log is untouched and the engineer can attach the redacted stream by piping it to a file, keeping the original for their own records.

Capturing token= rather than matching and discarding it is what lets the replacement rebuild the safe part of the line. Without the group you would either lose the token= label or have to type it out again in the replacement, and any typo there would silently corrupt the field name. Keeping the label in a back-reference ties the output's structure to the input's, which is the same discipline that made the price-report reformatting reliable.

The script has a real design flaw hiding in the character class. [A-Z0-9]+ matches only upper-case letters and digits, so it stops at the first character outside that set. A modern token is often base64, containing lower-case letters, /, +, and =; against token=AKIA/abc+123 the pattern matches only AKIA and produces token=REDACTED/abc+123, leaking most of the secret into the public ticket. The fix is to match the real token alphabet -- for example up to the next space with [^[:space:]]+ -- rather than guessing a narrow charset. This is the redaction trap in general: a mask that is too specific fails open, quietly passing through exactly the material it was meant to hide, which is far more dangerous than failing closed.


Common Mistakes

  1. Forgetting the g flag and replacing only the first match. s/,/;/ changes just the first comma on each line. When you mean every occurrence, you must write s/,/;/g; the default is first-match-only by design.
  1. Leaving a dot or other metacharacter unescaped. In a sed pattern . matches any character, so s/3.50/X/ also matches 3x50. Escape literals you mean literally: s/3\.50/X/.
  1. Using / as the delimiter when the data contains slashes. Rewriting a path with s/\/usr\/local/.../ is unreadable. sed lets you pick any delimiter, so s#/usr/local#/opt# is far clearer and needs no escaping.
  1. Expecting (...) and + to work in the default dialect. Basic sed needs \(, \), and \+; the operators are literal otherwise. Use sed -E for extended syntax so groups and quantifiers read normally.
  1. Running -i with no backup and a wrong pattern. In-place editing overwrites the file immediately; a bad pattern destroys the original with nothing to restore. Preview first, then use -i.bak to keep a copy.
  1. Believing sed edits the file by default. Without -i, sed only prints to standard output and the file is unchanged. People often "lose" their edits because they never redirected or committed them.
  1. Treating ^ and $ as document anchors. In sed they anchor to the start and end of each line, not the whole input, because sed works one line at a time. Multi-line matching needs the hold space or -z.
  1. Making a redaction pattern too narrow. A mask like [A-Z0-9]+ that misses part of a secret fails open, passing the sensitive tail through. Match the full token alphabet so the mask cannot leak.
  1. Forgetting case sensitivity. s/error/ERR/ will not touch Error or ERROR. Add the I flag, as in s/error/ERR/I, when case should not matter.

Best Practices

  • Preview before you commit. Run the command as a plain stream and read the output on screen; add -i only once the printed result is exactly right.
  • Always keep a backup with in-place edits. Use sed -i.bak so the original is preserved as file.bak and a wrong pattern is recoverable.
  • Choose a delimiter your data does not contain. s#...#...# or s|...|...| avoids a thicket of escaped slashes when editing paths or URLs.
  • Prefer -E for groups and quantifiers. Extended regular expressions let you write (...), +, and ? without backslashes, so complex patterns are easier to read and review.
  • Escape every literal metacharacter. Dots, asterisks, and brackets that should match themselves must be escaped, or they will match far more than you intended.
  • Anchor rewrites that must span the whole line. Use ^ and $ so a substitution meant for an entire field cannot fire on a fragment in the middle of the line.
  • Keep complex scripts readable. Break a multi-step edit into several -e clauses or a -f script file with comments, rather than one long unreadable expression.
  • Know when to switch tools. For column-structured or quoted data, awk or a real parser is safer than sed; reach for the right tool rather than forcing sed past its comfort zone.

Practice Exercises

  1. First versus global. Create a file whose lines each contain several commas. Run sed 's/,/;/' and sed 's/,/;/g' and record the difference. Explain in one sentence why the first form is rarely what you want.
  1. Reformat with groups. Given prices.txt, write a sed -E command that turns each name:colour:price line into price,name (just those two fields, comma-separated, colour dropped). Verify the output by eye.
  1. Safe in-place edit. Take a copy of a config file and use sed -i.bak to replace localhost with a real hostname. Show that the .bak file still contains localhost, and describe what you would have lost had you omitted the suffix.
  1. Close the redaction leak. Feed mask_log.sh a line whose token contains a / and show that part of the token survives. Then rewrite the pattern to mask up to the next space and confirm the whole token is replaced. State why a too-narrow mask is more dangerous than a too-wide one.