Does lookbehind work in sed?

后端 未结 2 1720
天命终不由人
天命终不由人 2020-12-01 10:48

I created a test using grep but it does not work in sed.

grep -P \'(?<=foo)bar\' file.txt

This works correctly

相关标签:
2条回答
  • 2020-12-01 11:09

    GNU sed does not have support for lookaround assertions. You could use a more powerful language such as Perl or possibly experiment with ssed which supports Perl-style regular expressions.

    perl -pe 's/(?<=foo)bar/test/g' file.txt
    
    0 讨论(0)
  • 2020-12-01 11:19

    Note that most of the time you can avoid a lookbehind (or a lookahead) using a capture group and a backreference in the replacement string:

    sed 's/\(foo\)bar/\1test/g' file.txt
    

    Simulating a negative lookbehind is more subtile and needs several substitutions to protect the substring you want to avoid. Example for (?<!foo)bar:

    sed 's/#/##/g;s/foobar/foob#ar/g;s/bar/test/g;s/foob#ar/foobar/g;s/##/#/g' file.txt
    
    • choose an escape character and repeat it (for example # => ##).
    • include this character in the substring you want to protect (foobar here, => foob#ar or ba => b#a).
    • make your replacement.
    • replace foob#ar with foobar (or b#a with ba).
    • replace ## with #.

    Obviously, you can also describe all that isn't foo before bar:

    sed -E 's/(^.{0,2}|[^f]..|[^o].?)bar/\1test/g' file.txt
    

    But it will be quickly fastidious with more characters.

    0 讨论(0)
提交回复
热议问题