1

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?

3
  • use set -x to see the interpolation of variable values as your cmd is being executed. Compare what you see there to your hard-coded version and then escape chars as need to get the same results. Good luck. Commented Mar 16, 2016 at 23:25
  • Thanks! I see the variables as my program executes. Maybe i should open a new thread... But it still seems very relevant here: the grep took a single quote as a result even though I used double quotes everywhere.. any suggestion to fix that? Commented Mar 16, 2016 at 23:36
  • I should have mentioned that. The single quote view is the shells way of showing "This is as far as I can rationalize what I have converted" . A single quoted string will also show up as single-quoted. And (I think) the shell will even single-quote strings where no quotes (of any type) where used, just to make clear "what it is processing" . Just edit your Q with the set -x view and add your comments about what still is not working. Good luck. Commented Mar 16, 2016 at 23:51

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

I used egrep instead of grep -E for the first case, but still same results. Any idea? I try to avoid escaping my {} because that will make it hard to read.
egrep for the first case worked fine for me as well. Testing it on RHEL 6.7 btw. I'd suggest you use single quotes for the pattern var. Also, what exact pattern are you using - with or without the trailing {3} ?
Does the "variable substitution" fail only when used in your program, or also from the command line? Could you post a complete transscript from the commandline, which shows the error, including doing an echo on the variable containing the pattern?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.