用前导减号替换尾随减号 [英] Replace a trailing minus with leading minus
问题描述
我正在尝试替换带有尾随减号的值,并用前导减号替换它们.我有这个在 SED 中不太适用的正则表达式,虽然我不明白为什么.
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 返回 8.8-
SED returns 8.8-
我在 Notepad++ RegEx Help 插件中尝试了匹配 8.8- 并将子匹配 \1 标识为 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
推荐答案
\d
是 Perlism.Sed 指的是较旧的、Perl 之前的 POSIX 标准.你可能想要的是
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/'
[[:digit:]]
是编写 Perl 的 \d
的 POSIX 方式.
The [[:digit:]]
is the POSIX way to write Perl's \d
.
当然,正如其他人指出的那样,您可以只写 [0-9]
.
Of course, you can just write [0-9]
, instead, as others have noted.
顺便说一句,您需要 -r
来使您的括号随心所欲.
Incidentally, you need the -r
to make your parentheses work as you like.
这篇关于用前导减号替换尾随减号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!