Linux sed - 如何使用 sed 做正则表达式组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11650940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed - how to do regex groups using sed
提问by Shengjie
Is there anyway you can do regex match group using sed like java regex pattern/match/group?
无论如何你可以像java regex pattern/match/group一样使用sed来做regex match group吗?
if i have string like
如果我有像这样的字符串
test-artifact-201251-balbal-0.1-SNAPSHOT.jar
how do I use sed just to get the result like:
我如何使用 sed 来获得如下结果:
test-artifact-0.1-SNASHOT.jar
I am wondering does sed allow you to do something like java regex, you define the pattern like:
我想知道 sed 是否允许您执行类似 java regex 的操作,您定义的模式如下:
([a-z]*-[a-z]*-)([0-9]*-)([a-z]*-)([.]*SNAPSHOT.jar)
and then you can get the results as an array like:
然后你可以得到一个数组的结果,如:
test-artifact-
201251-
balbal-
0.1-SNAPSHOT.jar
采纳答案by Birei
You have to escape parentheses to group expressions:
您必须转义括号才能对表达式进行分组:
\([a-z]*-[a-z]*-\)\([0-9]*-\)\([a-z]*-\)\([.]*SNAPSHOT.jar\)
And use them with \1
, \2
, etc.
并与使用它们\1
,\2
等等。
EDIT: Also note just before SNAPSHOT
that [.]
will not match. Inside brackets .
is literal. It should be [0-9.-]*
编辑:还要注意之前SNAPSHOT
那[.]
将不匹配。括号内.
是字面意思。它应该是[0-9.-]*
回答by Steve
This is what Birei and Thor mean:
这就是 Birei 和 Thor 的意思:
sed -r "s/([a-z]*-[a-z]*-)([0-9]*-)([a-z]*-)(.*)/\n\n\n/"
Output:
输出:
test-artifact-
201251-
balbal-
0.1-SNAPSHOT.jar
回答by Kent
infact for those regular string, awk could save you from grouping. :)
事实上,对于那些常规字符串,awk 可以使您免于分组。:)
you just give the part index number you want:
您只需提供所需的零件索引号:
awk 'BEGIN{FS=OFS="-"}{print ,,,}'
output:
输出:
kent$ echo "test-artifact-201251-balbal-0.1-SNAPSHOT.jar"|awk 'BEGIN{FS="-";OFS="-"}{print ,,,}'
test-artifact-0.1-SNAPSHOT.jar
回答by SAM80DEV
If you are searching for an easier way I guess this might be of your help! :)
如果您正在寻找一种更简单的方法,我想这可能对您有所帮助!:)
echo "est-artifact-201251-balbal-0.1-SNAPSHOT.jar" | cut -d- -f1,2,5,6
"-" used as delimeter and fields 1,2,5,6 are printed.
“-”用作分隔符并打印字段 1,2,5,6。
Note: This would require you to know the exact position of the field.
注意:这需要您知道该字段的确切位置。