Simple trouble with awk and regex

送分小仙女□ 提交于 2019-12-19 09:55:24

问题


 echo xx y11y rrr | awk '{ if ($2 ~/y[1-5]{2}y/) print $3}'

Why I cannot get any output?

Thank you.


回答1:


You need to enable "interval expressions" in regular expression matching by specifying either the --posix or --re-interval option.

e.g.

echo xx y11y rrr | awk --re-interval '{ if ($2 ~ /y[1-5]{2}y/) print $3}

From the man page:

--re-interval Enable the use of interval expressions in regular expression matching (see Regular Expressions, below). Interval expressions were not traditionally available in the AWK language. The POSIX standard added them, to make awk and egrep consistent with each other. However, their use is likely to break old AWK programs, so gawk only provides them if they are requested with this option, or when --posix is specified.




回答2:


You should force POSIX to use {} in awk

echo xx y11y rrr | awk -W posix '{ if ($2 ~/y[1-5]{2}y/) print $3}'



回答3:


On my machine:

$ echo xx y11y rrr | awk '{ if ($2 ~/y[1-5]{2}y/) print $3}'
rrr

Was this what you wanted? I'm using GNU awk 4.0.0 in Cygwin on Windows XP.



来源:https://stackoverflow.com/questions/8343058/simple-trouble-with-awk-and-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!