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
  • Storage memory
  • contains at least '\n'
 

Syntax

$ sed 'command' file

Processing

  1. sed copies the first line of the input file in the pattern space
  2. sed applies the command(s) in between quotes to the pattern space
  3. sed moves the pattern space content to the output
  4. sed goes to the next line of the file and repeats operation 1

Main commands

For the pattern space

CommandDescription
pprints PS content
ddeletes PS content
=prints PS line number
nmoves PS to OUT and IN to PS
Ncopies next line from IN to PS
Pprints first line of PS to OUT
Ddeletes first line of PS
s/x/yreplaces x by y in the PS
s/x/y/pidem then prints PS content
s/x/y/g(GLOBAL) idem but replaces as much as possible
s/x/y/Iidem but case-insensitive
y/abc/defreplaces characters a, b, c by d, e, f respectively
w examplewrites in file
s/x/y/w fileidem and write the modified lines in the file
r filecopies file's content in the PS
qstops execution and moves PS to OUT
Qstops execution, does not perform stages 3 and 4
#comment
aAPPEND - appends a line after
iINSERT - appends a line before
cCHANGE - change the line (idem Vim)

For the hold space

CommandDescription
xswaps PS and HS
hHOLD - copies PS to HS
gGET - moves HS to PS
Hadds PS to HS
Gadds 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