67

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
$
mike_b
  • 2,127
  • 5
  • 20
  • 25
  • 3
    Well, I think I figured out it works with double quotes. – mike_b Aug 09 '13 at 13:36
  • 2
    Correct, double quotes. Just remember that within double quotes you have to escape backslashes and the EOL `$`. – Kevin Aug 09 '13 at 13:39
  • possible duplicate of [Add grep command to bash script](http://stackoverflow.com/questions/5142729/add-grep-command-to-bash-script) – tripleee Sep 05 '13 at 17:14

1 Answers1

75

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}"
Francisco Puga
  • 23,869
  • 5
  • 48
  • 64
David W.
  • 105,218
  • 39
  • 216
  • 337
  • 2
    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. – Leo Jul 11 '21 at 03:58