Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - variable expansion within backtick/grep regex string

I'm trying to expand a variable in my bash script inside of the backticks, inside of the regex search string.

I want the $VAR to be substituted.

The lines I am matching are like:

start....some characters.....id:.....some characters.....[variable im searching for]....some characters....end

var=`grep -E '^.*id:.*$VAR.*$' ./input_file.txt`

Is this a possibility?

It doesn't seem to work. I know I can normally expand a variable with "$VAR", but won't this just search directly for those characters inside the regex? I am not sure what takes precedence here.

like image 644
krb686 Avatar asked Mar 05 '15 13:03

krb686


1 Answers

Variables do expand in backticks but they don't expand in single quotes.

So you need to either use double quotes for your regex string (I'm not sure what your concern with that is about) or use both quotes.

So either

var=`grep -E "^.*id:.*$VAR.*$" ./input_file.txt`

or

var=`grep -E '^.*id:.*'"$VAR"'.*$' ./input_file.txt`

Also you might want to use $(grep ...) instead of backticks since they are the more modern approach and have better syntactic properties as well as being able to be nested.

like image 92
Etan Reisner Avatar answered Sep 28 '22 14:09

Etan Reisner