What's wrong with my lookahead regex in GNU sed?

sed -i '/^foo/! s/^/bar/' file.txt
  • -i change the file in place
  • /^foo/! only perform the next action on lines not ! starting with foo ^foo
  • s/^/bar/ change the start of the line to bar  

As far as I know sed has not neither look-ahead nor look-behind. Switch to a more powerful language with similar syntax, like perl.


You use perl compatible regular expression (PCRE) syntax which is not supported by GNU sed. You should rewrite your regex according to SED Regular-Expressions or use perl instead.

Note that SED doesn't have lookahead and therefore doesn't support the regex feature you were trying to use. It can be done in SED using other features, as others have mentioned.