I'm trying to replace values which have a trailing minus sign and replace them with a leading minus sign. I've got this regex which doesn't quite work in SED though I don't understand why.
echo '8.8-' | sed 's/(\d+(?:\.\d+)?)-/-\\1/'
SED returns 8.8-
I tried the expression in Notepad++ RegEx Help plugin which matches the 8.8- and identifies the sub-match \1 as 8.8
The \d is a Perlism. Sed refers to the older, pre-Perl, POSIX standard. What you probably want is
echo '8.8-' | sed -r 's/([[:digit:]]+(\.[[:digit:]]+)?)-/-\1/'
The [[:digit:]] is the POSIX way to write Perl's \d.
Of course, you can just write [0-9], instead, as others have noted.
Incidentally, you need the -r to make your parentheses work as you like.
\d does not match a digit character class in sed, [0-9] will though.
BTW please include what it is you're REALLY trying to do - are you working with numbers? Ints and decimal? I can deduce as much from your RegEx but shouldn't need to if the question is asked properly.
EDIT
If you're using GNU linux, better to use character classes than traditional ranges as they're more portable:
echo '8.8-' | sed -r 's/([[:digit:]]+(\.[[:digit:]]+)?)-/-\1/'
http://sed.sourceforge.net/sedfaq3.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With