cmo
cmo

Reputation: 4104

sed line range not respected if match on first line

I am trying to parse a file that looks as follows:

$ echo -e "[Header]\nbar\nfoo\n[more]\na\nb"
[Header]
bar
foo
[body]
a
b

Suppose I want everything after the [body] line. I can do this:

$ sed  -e  '1,/^\[body\]/d'   
a
b

But that analogous command does not work if I want everything after the [Header] line:

$ sed  -e  '1,/^\[Header\]/d' 

produces nothing.

Why doesn't sed seem to respect the line range, which is effectively 1,1 in the second command?

While there are certainly alternative approaches to get the desired result (such as here, suggested in a comment below by @Wiktor Stribiżew), this question is about why the above command does not work.

Upvotes: 0

Views: 136

Answers (2)

dash-o
dash-o

Reputation: 14424

The info sed states:

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).

While it is possible to argue for other interpretations (which will allow for single line match), this decision was made long time ago, and is hard to change because of compatibility issue.

Upvotes: 2

AlexP
AlexP

Reputation: 4430

From the manual page of Gnu sed:

Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address.

Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched.

Upvotes: 3

Related Questions