74

I'm trying to use a variable in a grep regex. I'll just post an example of the failure and maybe someone can suggest how to make the variable be evaluated while running the grep command. I've tried ${var} as well.

$ string="test this"
$ var="test"
$ echo $string | grep '^$var'
$ 

Since my regex should match lines which start with "test", it should print the line echoed thru it.

$ echo $string
test this
$
3
  • 3
    Well, I think I figured out it works with double quotes. Commented Aug 9, 2013 at 13:36
  • 2
    Correct, double quotes. Just remember that within double quotes you have to escape backslashes and the EOL $. Commented Aug 9, 2013 at 13:39
  • possible duplicate of Add grep command to bash script Commented Sep 5, 2013 at 17:14

1 Answer 1

79

You need to use double quotes. Single quotes prevent the shell variable from being interpolated by the shell. You use single quotes to prevent the shell from doing interpolation which you may have to do if your regular expression used $ as part of the pattern. You can also use a backslash to quote a $ if you're using double quotes.

Also, you may need to put your variable in curly braces ${var} in order to help separate it from the rest of the pattern.

Example:

$ string="test this"
$ var="test"
$ echo $string | grep "^${var}"
Sign up to request clarification or add additional context in comments.

1 Comment

How would I also additionally use an end-line anchor $ in this expression? e.g. I've tried grep "^$var$" and it doesn't seem to work. EDIT: Nvm, grep "^$var$" does seem to work. I had some other syntax wrong.

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.