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

RegexLinuxSedRegex Lookarounds

Regex Problem Overview


This is what I'm doing (simplified example):

gsed -i -E 's/^(?!foo)(.*)$/bar\1/' file.txt

I'm trying to put bar in front of every line that doesn't start with foo. This is the error:

gsed: -e expression #1, char 22: Invalid preceding regular expression

What's wrong?

Regex Solutions


Solution 1 - Regex

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  

Solution 2 - Regex

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.

Solution 3 - Regex

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyegor256View Question on Stackoverflow
Solution 1 - RegexkkellerView Answer on Stackoverflow
Solution 2 - RegexBireiView Answer on Stackoverflow
Solution 3 - RegexhostmasterView Answer on Stackoverflow