带有可选小数和反向引用的 sed 数字 [英] sed digits with optional decimal and backreference
问题描述
我有这样的简单输入:
11111(n)
222222(p)
33333333(:)
我可以使用 sed 反向引用将括号与这样的数字交换:
I can use sed backreference to swap parenthesis with digits like this :
sed -e 's/\([[:digit:]]*\)\((.*)\)/\2 \1/' file
产生
(n) 11111
(p) 222222
(:) 33333333
很酷!
但是对于潜在的十进制数字,事情变得更加困难,就像这样
But things became more difficult with potential decimal digits, like this
11111(n)
11111.111(n)
2222222.22(p)
33.3333333(:)
我尝试了很多命令,比如
I've try many commands, like
sed -e 's/\([[:digit:]]*(\.[[:digit:]]*?)\)\((.*)\)/\2 \1/' file
sed -e 's/\([[:digit:]]*\.?[[:digit:]]*?)\)\((.*)\)/\2 \1/' file
sed -e 's/\([[:digit:]]*\.*[[:digit:]]*)\)\((.*)\)/\2 \1/' file
sed -e 's/\([[:digit:]]*.*[[:digit:]]*)\)\((.*)\)/\2 \1/' file
所需的输出:
(n) 11111
(n) 11111.111
(p) 2222222.22
(:) 33.3333333
注意数字可以是任意长(1到n位),小数点(.)和十进制数字是可选的.
Note that digits can be arbitrary long (1 to n digits), and decimal mark (.) and decimal digits are optional.
此外,sed
似乎没有 \d
速记,正如 stackexchange
Furthermore, sed
don't seem to have \d
shorthand, as pointed in stackexchange
推荐答案
当您知道在 POSIX 括号表达式中使用 [:digit:]
匹配什么时,它变得非常简单.您需要做的就是包含另一个 .
以便括号表达式将表示与 .
,
It gets quite simple when you know what to match in the POSIX bracket expression with [:digit:]
. All you need to do is include another .
so that the bracket expression would mean set of digits along with .
,
sed 's/\([[:digit:].]*\)\((.*)\)/\2 \1/' file
另外你不需要提到-e
,因为sed
默认在BRE(基本正则表达式)模式下运行,并且带有-E代码> 启用了 ERE(扩展正则表达式)模式.此外,
\d
不是任何版本的 sed
(POSIX、GNU 或 FreeBSD)用来匹配数字的有效正则表达式构造.我想它在 PCRE 库中受支持,您可以在其中使用 perl
Also you don't need to mention -e
, because sed
by default operates in BRE (Basic Regular Expressions) mode and with -E
the ERE (Extended Regular Expression) mode is enabled. Also \d
is not a valid regular expression construct used by any versions of sed
(POSIX, GNU or FreeBSD) to match digits. I suppose it is supported in the PCRE library in which you could use perl
perl -lne 'print "$2 $1" if /(\d+\.?\d*).*(\([^)]*\))/' file
这篇关于带有可选小数和反向引用的 sed 数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!