[英]How to pass regular expression pattern as a variable to grep?
For example, I have a regex to match xx-xx-xxx
: [a-z0-9]{2}-[a-z0-9]{2}-[a-z0-9]{3}
, I want to store it to a variable so I can keep referring to it in my program. 例如,我有一个正则表达式匹配xx-xx-xxx
: [a-z0-9]{2}-[a-z0-9]{2}-[a-z0-9]{3}
,我想要将其存储到变量中,这样我就可以在程序中继续引用它。 Here is what I tried: 这是我尝试过的:
pattern="[a-z0-9]{2}-[a-z0-9]{2}-[a-z0-9]"
grep -i "here:$pattern" file.log # assuming that my log file has "hi:xx-xx-xxx" pattern strings.
No results are returned but if I execute: 没有结果返回,但是如果我执行:
grep -i "here:[a-z0-9]{2}-[a-z0-9]{2}-[a-z0-9]" file.log
It works. 有用。 What did I do wrong? 我做错了什么?
You either have to escape the curly brackets like so \\{2\\}
or use the extended regexp mode of grep via the -E
flag. 您要么必须转义\\{2\\}
这样的大括号,要么通过-E
标志使用grep的扩展正则表达式模式。 Thus it'll be either 因此,要么
pattern='[a-z0-9]{2}-[a-z0-9]{2}-[a-z0-9]{3}'
echo "hi:aa-00-xxx" | grep -iE "hi:$pattern"
or 要么
pattern='[a-z0-9]\{2\}-[a-z0-9]\{2\}-[a-z0-9]\{3\}'
echo "hi:aa-00-xxx" | grep -i "hi:$pattern"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.