Sed/sed-script-overview
Next: sed commands list, Up: sed scripts [Contents][Index]
3.1 sed
script overview
A sed
program consists of one or more sed
commands,
passed in by one or more of the
-e
, -f
, --expression
, and --file
options, or the first non-option argument if zero of these
options are used.
This document will refer to “the” sed
script;
this is understood to mean the in-order concatenation
of all of the script
s and script-file
s passed in.
See Overview.
sed
commands follow this syntax:
[addr]X[options]
X
is a single-letter sed
command.
[addr]
is an optional line address. If [addr]
is specified,
the command X
will be executed only on the matched lines.
[addr]
can be a single line number, a regular expression,
or a range of lines (see sed addresses).
Additional [options]
are used for some sed
commands.
The following example deletes lines 30 to 35 in the input.
30,35
is an address range. d
is the delete command:
sed '30,35d' input.txt > output.txt
The following example prints all input until a line
starting with the word ‘foo
’ is found. If such line is found,
sed
will terminate with exit status 42.
If such line was not found (and no other error occurred), sed
will exit with status 0.
/^foo/
is a regular-expression address.
q
is the quit command. 42
is the command option.
sed '/^foo/q42' input.txt > output.txt
Commands within a script
or script-file
can be
separated by semicolons (;
) or newlines (ASCII 10).
Multiple scripts can be specified with -e
or -f
options.
The following examples are all equivalent. They perform two sed
operations: deleting any lines matching the regular expression /^foo/
,
and replacing all occurrences of the string ‘hello
’ with ‘world
’:
sed '/^foo/d ; s/hello/world/' input.txt > output.txt sed -e '/^foo/d' -e 's/hello/world/' input.txt > output.txt echo '/^foo/d' > script.sed echo 's/hello/world/' >> script.sed sed -f script.sed input.txt > output.txt echo 's/hello/world/' > script2.sed sed -e '/^foo/d' -f script2.sed input.txt > output.txt
Commands a
, c
, i
, due to their syntax,
cannot be followed by semicolons working as command separators and
thus should be terminated
with newlines or be placed at the end of a script
or script-file
.
Commands can also be preceded with optional non-significant
whitespace characters.
See Multiple commands syntax.
Next: sed commands list, Up: sed scripts [Contents][Index]