我想匹配hyphen和hash sign在while循环awk。我目前的设置是:
awk 'BEGIN { while ($1==# && $2==-) { #do stuff} }'
Run Code Online (Sandbox Code Playgroud)
这显然会导致哈希符号出现语法错误。我尝试过以各种方式转义它,但这要么导致语法错误,要么导致“反斜杠不是最后一个字符”错误。
所以:我怎样才能匹配hash sign,并hyphen在awk表达?
在while一个BEGIN可能不是你想要的,除非#do stuff包括next或一些其他的语句获取输入的下一行。为了回答您的具体问题,我假设您要检查每一行输入。我使用echo -e 'foo bar skip\n# - printme'提供两行输入:foo bar skipand # - printme,我使用print $3代替#do stuff.
echo -e 'foo bar skip\n# - printme' | awk '($1=="#" && $2=="-") { print $3 }'
# ^ ^ ^ ^ double quotes
Run Code Online (Sandbox Code Playgroud)
打印printme,因为它应该。你也可以用正则表达式做到这一点:
echo -e 'foo bar skip\n# - printme' | awk '($1~/^#$/ && $2~/^-$/) { print $3} '
# ^^ ^ ^^ ^ regex match
Run Code Online (Sandbox Code Playgroud)
该~是正则表达式匹配运算符和//分隔正则表达式。 编辑The ^and $are so the regex 匹配整个字段,如果,例如,$1只包含一个连字符,则不会成功。
在 cygwin 上的 gawk 4.1.3 上测试。