bash 如何使用`awk`打印正则表达式匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5466411/
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 print regexp matches using `awk`?
提问by Istvan
Is there a way to print a regexp match (but only the matching string) using awk
command in shell?
有没有办法awk
在 shell 中使用命令打印正则表达式匹配(但只有匹配的字符串)?
回答by SiegeX
Yes, in awk
use the match()
function and give it the optional array parameter (a
in my example). When you do this, the 0-th element will be the part that matched the regex
是的,在awk
使用该match()
函数并为其提供可选的数组参数(a
在我的示例中)。执行此操作时,第 0 个元素将是与正则表达式匹配的部分
$ echo "blah foo123bar blah" | awk '{match(,"[a-z]+[0-9]+",a)}END{print a[0]}'
foo123
回答by Joshua Cook
An awk
specific (as opposed to one using gawk
) implementation of the solution:
解决方案的awk
特定(而不是使用gawk
)实现:
$ echo "blah foo123bar blah" | awk 'match(split(substr(##代码##, match(##代码##, /[0-9]+ [Bb]ytes/)), a, " ");
print a[1];
,/[a-z]+[0-9]+/) {print substr(##代码##,RSTART,RLENGTH)}'
foo123
回答by nyet
I use this construct quite a bit:
我经常使用这个结构:
##代码##