The Sed Execution Cycle
sed processes input one line at a time.
For each line:
Read one line
↓
Store it in Pattern Space
↓
Execute all commands
↓
Print the Pattern Space
↓
Discard it
↓
Read the next lineThe temporary buffer holding the current line is called the Pattern Space.
Each line is processed independently unless advanced commands (N, H, G, etc.) are used.
Mental Model
Think:
For every line:
Does the address match?
If yes, execute the command(s).
This explains most sed behavior.
Addresses
General syntax:
address commandExample:
sed '2s/a/A/g'Only line 2 is modified.
Line Number Address
Modify line 3:
sed '3s/.*/FOUND/'Delete line 5:
sed '5d'Line Range
Operate on lines 10–20:
sed '10,20d'Last Line
$ represents the last line.
Delete the last line:
sed '$d'Print only the last line:
sed -n '$p'Pattern Address
Execute a command only on matching lines.
Replace text:
sed '/banana/s/a/A/g'Delete matching lines:
sed '/ERROR/d'Negation
! means “all lines except.”
Example:
sed '/ERROR/!s/o/O/g'Every line except those containing ERROR is modified.
Multiple Commands
Using multiple -e options:
sed -e '1d' -e '$d'Or in a script:
sed '
1d
$d
'Commands are executed in order.
Vim Comparison
Many sed commands are identical to Vim Ex commands.
| Vim | sed |
|---|---|
:%s/a/b/g | s/a/b/g |
:5d | 5d |
:10,20d | 10,20d |
:/ERROR/d | /ERROR/d |
The major difference:
-
Vim edits the whole file interactively.
-
sed processes one line at a time automatically.
Key Takeaways
-
sedworks on one line at a time. -
The current line is stored in the Pattern Space.
-
Addresses decide where commands execute.
-
Commands execute sequentially for each input line.
-
Most everyday
sedusage combines addresses withs,d,p,i,a, orc.