0

These commands work as expected: Case 1, 2:

$ printf "a\nb\nc\n" | sed -n '/a/ p'
a

$ printf "a\nb\na\n" | sed -n '/a/,/a/ p'
a
b
a

however I expected the following command to match only 'a', and I'm having trouble understanding the documented definition of two address ranges:

Case 3, 4:

$ printf "a\nb\nc\n" | sed -n '/a/,/a/ p'
a
b
c

$ printf "a\nb\nc\n" | sed -n '/b/,/b/ p'
b
c

Can anyone further explain this the behavior of this definition?

SED Command: [addr[,addr]f[args]

$ man sed

"...In the case when the second address is a context address, sed does not re-match the second address against the pattern space that matched the first address. Starting at the first line following the selected range, sed starts looking again for the first address..."

Thanks

1

The important part is this:

sed does not re-match the second address against the pattern space that matched the first address

The last part of your quote is rather confusing; I prefer this section of the manpage I have:

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.

The last “thing to note” explains the behaviour you’re seeing. When you run

printf "a\nb\nc\n" | sed -n '/a/,/a/ p'

sed matches /a/, and then continues copying its pattern space until it matches /a/ again, on a different line, which never happens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.