简体   繁体   中英

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.

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.

You need to have the expression in double quotes (and, then, escape anything which needs to be escaped) in order for the variable to be interpolated.

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

(The backslash is not strictly necessary here, but I put it in to give you an idea. Your real expression is perhaps more complex.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM