BASH:如何在AWK中使用变量作为正则表达式 [英] BASH: How to use a variable as regex in AWK

查看:494
本文介绍了BASH:如何在AWK中使用变量作为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了几个小时在Awk教程上,但是我无法解决这个问题: 我想将变量用作awk查询的正则表达式.这是我要实现的示例:

I have spent hours on Awk tutorials but I can not get around that one: I want to use a variable as a regex for a awk query. Here is an example of what i want to achieve:

#!/bin/bash
#My test array
testarray=(teststring[1078] teststringthatshouldnotmatch teststring[5845])

#myregex as a variable
regex="teststring\[.*"

#the awk
for value in ${testarray[*]}
do
echo ${value} | awk '{if ($1 ~ regex) print}'
done

我希望Awk能够匹配测试字符串1和3,但是它匹配所有字符串.感谢您对此有任何了解.

I woud expect Awk to match teststring 1 and 3 but it matches all. Thanks for any light on this one.

推荐答案

在正则表达式上下文中使用字符串时,您需要对要转义的所有内容进行两次转义.总是引用您的shell变量,并且不需要调用match(),您应该将条件放在awk脚本的条件部分中,而不是在操作部分的if中,并且不需要显式打印.另外,.*表示任何字符的零个或多个重复,因此匹配零个字符,因此对您的正则表达式没有任何帮助.您只需要:

When using a string in a regexp context you need to escape twice anything you want escaped. Always quote your shell variables, and there's no need to call match(), and you should put the condition inthe condition section of the awk script, not inside an if in the action part, and there's no need for an explicit print. Also, .* means zero or more repetitions of any char and so matches zero chars and so is doing nothing useful for your regexp. All you need is:

regex='teststring\\['
...
awk -v test="$regex" '$1~test'

看:

$ cat tst.sh
#!/bin/bash
#My test array
testarray=(teststring[1078] teststringthatshouldnotmatch teststring[5845])

#myregex as a variable
regex='teststring\\['

#the awk
for value in "${testarray[@]}"
do
    echo "$value" | awk -v test="$regex" '$1 ~ test'
done
$
$ ./tst.sh
teststring[1078]
teststring[5845]

这篇关于BASH:如何在AWK中使用变量作为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆