Reputation: 4366
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. 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?
Upvotes: 1
Views: 1054
Reputation: 7656
You either have to escape the curly brackets like so \{2\}
or use the extended regexp mode of grep via the -E
flag.
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"
Upvotes: 1