Tuesday, October 25, 2016

Using extended regular expressions in sed

I've never quite figured out Posix regular expressions, and was trying to replace the first n characters for every line in a file the other day using sed. This is easy if all the lines have at least n characters in them.
sed s/^....//

But sed doesn't suppor the "optional" question mark modifier so lines with less than n characters would not be matched.

It turns out you can turn on extended regex support with "-r" or "--regexp-extended" allowing the following.
sed s/^.?.?.?.?//