Sed /
Usage
Meaning
sed means *Stream EDitor*.
Main options
-e
-e allows sequential execution of several instruction sets.
-i
-i allows the input file to be modified
Principle
Sed works with 4 zones :
- input (IN)
- pattern space (PS)
- output (OUT)
- hold space (HS)
INPUT
| PATTERN SPACE
| OUTPUT
|
---|---|---|
HOLD SPACE
|
Syntax
$ sed 'command' file
Processing
- sed copies the first line of the input file in the pattern space
- sed applies the command(s) in between quotes to the pattern space
- sed moves the pattern space content to the output
- sed goes to the next line of the file and repeats operation 1
Main commands
For the pattern space
Command | Description |
---|---|
p | prints PS content |
d | deletes PS content |
= | prints PS line number |
n | moves PS to OUT and IN to PS |
N | copies next line from IN to PS |
P | prints first line of PS to OUT |
D | deletes first line of PS |
s/x/y | replaces x by y in the PS |
s/x/y/p | idem then prints PS content |
s/x/y/g | (GLOBAL) idem but replaces as much as possible |
s/x/y/I | idem but case-insensitive |
y/abc/def | replaces characters a, b, c by d, e, f respectively |
w example | writes in file |
s/x/y/w file | idem and write the modified lines in the file |
r file | copies file's content in the PS |
q | stops execution and moves PS to OUT |
Q | stops execution, does not perform stages 3 and 4 |
# | comment |
a | APPEND - appends a line after |
i | INSERT - appends a line before |
c | CHANGE - change the line (idem Vim) |
For the hold space
Command | Description |
---|---|
x | swaps PS and HS |
h | HOLD - copies PS to HS |
g | GET - moves HS to PS |
H | adds PS to HS |
G | adds HS to PS |
Debugging
Debugging can be done with 'l' command. It prints PS then breaks. To print the PS after command processing, use the following:
$ sed 'n; l;' file
Labels
The command ':' defines a label that can be reused with command 'b' (BRANCH)
- 't' goes to the label if a replacement has been done
- 'T' goes to the label if no replacement has been done