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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:20:41  来源:igfitidea点击:

How to print regexp matches using `awk`?

bashshellawk

提问by Istvan

Is there a way to print a regexp match (but only the matching string) using awkcommand in shell?

有没有办法awk在 shell 中使用命令打印正则表达式匹配(但只有匹配的字符串)?

回答by SiegeX

Yes, in awkuse the match()function and give it the optional array parameter (ain 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 awkspecific (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:

我经常使用这个结构:

##代码##