bash 如何让 sed 进行非贪婪匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18791351/
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
How to make sed do non-greedy match?
提问by Red Cricket
I cannot seem to figure out how to come up with the correct regex for my bash command line. Here's what I am doing:
我似乎无法弄清楚如何为我的 bash 命令行提出正确的正则表达式。这是我在做什么:
echo "XML-Xerces-2.7.0-0.tar.gz" | sed -e's/^\(.*\)-[0-9].*//g'
This gives me the output of ...
这给了我...的输出
XML-Xerces-2.7.0
... but want I need is the output to be ...
...但我需要的是输出是...
XML-Xerces
... I guess I could do this ...
......我想我可以做到这一点......
echo "XML-Xerces-2.7.0-0.tar.gz" | sed -e's/^\(.*\)-[0-9].*//g' | sed -e's/^\(.*\)-[0-9].*//g'
... but I would like to know how understand sed
regex a little better.
...但我想知道如何sed
更好地理解正则表达式。
Update:
更新:
I tried this ...
我试过这个...
echo "XML-Xerces-2.7.0-0.tar.gz" | sed -e's/^\([^-]*\)-[0-9].*//g'
... as suggest but that outputs XML-Xerces-2.7.0-0.tar.gz
...正如建议的那样,但输出 XML-Xerces-2.7.0-0.tar.gz
回答by Paul
You can't do non greedy regex in sed, but you can do something like this instead:
你不能在 sed 中做非贪婪的正则表达式,但你可以做这样的事情:
echo "XML-Xerces-2.7.0-0.tar.gz" | sed -e 's/^\(\([^-]\|-[^0-9]\)*\).*//g'
Which will capture everything up until it finds a -
followed by [0-9]
.
这将捕获所有内容,直到找到-
后跟[0-9]
.
回答by konsolebox
You actually don't sed when you're in bash:
当你在 bash 中时,你实际上并没有 sed:
shopt -s extglob
V='XML-Xerces-2.7.0-0.tar.gz'
echo "${V%%-+([0-9]).+([0-9])*}"