Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 654
yegor256 Avatar asked Aug 29 '12 10:08

yegor256


People also ask

Does SED support lookahead?

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.

Can I use regex lookahead?

Lookahead assertions are part of JavaScript's original regular expression support and are thus supported in all browsers.

What is a lookahead in regex?

Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser's current position. They don't match anything. Hence, they are called as zero-width assertions.

Does SED support Lookbehind?

I created a test using grep but it does not work in sed . This works correctly by returning bar . I was expecting footest as output, but it did not work. sed does not support lookaround assertions.


1 Answers

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  
like image 159
kkeller Avatar answered Oct 22 '22 03:10

kkeller