Sed/Range-Addresses
Previous: Regexp Addresses, Up: sed addresses [Contents][Index]
4.4 Range Addresses
An address range can be specified by specifying two addresses
separated by a comma (,
). An address range matches lines
starting from where the first address matches, and continues
until the second address matches (inclusively):
$ seq 10 | sed -n '4,6p' 4 5 6
If the second address is a regexp
, then checking for the
ending match will start with the line following the
line which matched the first address: a range will always
span at least two lines (except of course if the input stream
ends).
$ seq 10 | sed -n '4,/[0-9]/p' 4 5
If the second address is a number
less than (or equal to)
the line matching the first address, then only the one line is
matched:
$ seq 10 | sed -n '4,1p' 4
GNU sed
also supports some special two-address forms; all these
are GNU extensions:
0,/regexp/
A line number of
0
can be used in an address specification like0,/regexp/
so thatsed
will try to matchregexp
in the first input line too. In other words,0,/regexp/
is similar to1,/regexp/
, except that ifaddr2
matches the very first line of input the0,/regexp/
form will consider it to end the range, whereas the1,/regexp/
form will match the beginning of its range and hence make the range span up to the second occurrence of the regular expression.Note that this is the only place where the
0
address makes sense; there is no 0-th line and commands which are given the0
address in any other way will give an error.The following examples demonstrate the difference between starting with address 1 and 0:
$ seq 10 | sed -n '1,/[0-9]/p' 1 2 $ seq 10 | sed -n '0,/[0-9]/p' 1
addr1,+N
Matches
addr1
and theN
lines followingaddr1
.$ seq 10 | sed -n '6,+2p' 6 7 8
addr1
can be a line number or a regular expression.addr1,~N
Matches
addr1
and the lines followingaddr1
until the next line whose input line number is a multiple ofN
. The following command prints starting at line 6, until the next line which is a multiple of 4 (i.e. line 8):$ seq 10 | sed -n '6,~4p' 6 7 8
addr1
can be a line number or a regular expression.
Previous: Regexp Addresses, Up: sed addresses [Contents][Index]