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

yegor256 picture yegor256 · Aug 29, 2012 · Viewed 37.2k times · Source

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?

Answer

kkeller picture kkeller · Aug 29, 2012
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