6

Is it possible to make lookahead or lookbehind zero-width assertions in sed? I want to emulate Perl's (?=) and family.

My sed is not GNU sed version 4.0.

1 Answers1

3

No, there aren't. You only have basic regular expressions, which only have character sets (. and […]), repetition (* and \{m,*n*\}), line anchors (^ and $) and grouping \(…\), plus backreferences \N. Some sed implementations have more repetition syntax (\+ and \?), alternation (\|), additional anchors (\b, \B, \<, \>). None that I know of have general zero-width assertions, you need to turn to Perl (or other tools that support PCRE) for that.

Many uses of zero-width assertions can be emulated with general regular expressions, using backreferences. For example, the Perl s/foo(?=bar)/FOO/ can be written s/foo\(bar\)/FOO\1/.

  • Backreferences fail if the backreferenced part needs to be matched right after too, though. One point of zero-with matching is that you can still match on those parts separately. –  Jul 18 '22 at 02:45