5

What is the POSIX behavior of the sed ^ and $ anchors when used at the beginning and end of a regex if the pattern space contains embedded newlines, like after you use the N command?

Should they still match the beginning and end of the pattern space or should they match the beginning and end of any line now that it contains multiple lines?

GNU sed's ^ and $ still match only the beginning and end of the entire pattern space.

1 Answer 1

3

^ and $ in BRE always match at the start and end of line, as describe here.

Any sed which use BRE will do the same way. In case of using N command, sed saw multi lines as one long line in pattern space, with each real line separated by embedded newline \n (literal \ and n).

For confirmation:

printf '1\n2\n' | sed '1N;/2$/d'

output nothing. And:

printf '1\n2\n' | sed '1N;/1$/d'

gave you:

1
2

Or using look command for more verbose:

$ printf '1\n2\n' | sed 1N\;l
1\n2$
1
2

$ printf '1\n2\n' | sed 1N\;l | od -t a
0000000   1   \   n   2   $  nl   1  nl   2  nl
0000012
7
  • 1
    IMO, the spec has a bug at the link you're giving here. Commented Aug 18, 2015 at 10:44
  • @StéphaneChazelas: Yeap, I also questioned about that. I'm looking for definition of what line mean in spec.
    – cuonglm
    Commented Aug 18, 2015 at 10:51
  • @cuonglm this is why I asked the question. I read one thing that suggested sed anchors behaved like Python's in MULTILINE mode, but they clearly don't, so I looked at the spec but couldn't figure it out
    – user129102
    Commented Aug 18, 2015 at 11:01
  • @StéphaneChazelas: perldoc perlre seems to be more obvious in this case, since when it also use the term string for ^ and $ by default, and define string is one line only.
    – cuonglm
    Commented Aug 18, 2015 at 11:01
  • @user129102: Can you give the link gave you the suggestion? sed anchors behaved like Python re without MULTILINE mode.
    – cuonglm
    Commented Aug 18, 2015 at 11:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .