'Capturing groups and interval quantifiers do not work in sed regex
In Linux I can run the command:
sed -r 's/^(.{2})0(.*)$/\1\2/' filename
However when running in UNIX I cant do -r so I tried:
sed 's/^(.{2})0(.*)$/\1\2/' filename
I get the following error:
sed: command garbled: s/^(.{2})0(.*)$/\1\2/
I feel like there is an easy fix but I cant figure it out.
Solution 1:[1]
The following is working for me:
sed 's/^\(.\{2\}\)0\(.*\)$/\1\2/'
You need to escape (){}
Edit: This will also solve your problem and is shorter. There is no need to continue searching to the end of the line.
sed 's/^\(.\{2\}\)0/\1/'
Solution 2:[2]
The quantifier syntax {n,m} and capture groups are part of the extended regexp class. By default sed uses only basic regular expression. If you read the man pages on your Linux system you can see what -r does:
-r, --regexp-extended use extended regular expressions in the script.
Check the man pages for sed on your Unix box and look if there is an equivalent option (possibly -E) or escape the ERE features.
See here for difference between BRE and ERE.
Solution 3:[3]
sed 's/^\(.\{2\}\)0\(.*\)$/\1\2/' <filename>
Read the manual for more details on regular expressions, or just google. Randomly removing arguments is unlikely to work (though kudos for "saying what you tried").
Solution 4:[4]
Not all seds are created equal. RE interval expressions like .{2} are part of modern Extended Regular Expressions (ERE)s while sed historically supports Basic Regular Expressions (BRE)s. Some seds on some machines simply will NOT support EREs so then you need to re-write your expression as a BRE (..) or switch to a different tool. Once you get to that new tool you still have issues because "RE Intervals" are a relatively recent addition to EREs so even with a tool like awk which supports EREs, not all awks will support RE Intervals. Some seds will support RE Intervals by puting backslahes before the braces, some will support them by you adding a flag like -r to tell sed that {2} means an RE Interval instead of literally {2}.
So, it's a bit of a mess BUT if you have a modern sed then chances are adding the -r flag will work for you and if you have a POSIX awk or a recent GNU awk then RE intervals will simply work by default.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Seymour |
| Solution 2 | |
| Solution 3 | Nicholas Wilson |
| Solution 4 | Ed Morton |
