简体   繁体   English

Bash脚本 - 反引号/ grep正则表达式字符串中的变量扩展

[英]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. 我正在尝试在正则表达式搜索字符串内部的反引号内部扩展我的bash脚本中的变量。

I want the $VAR to be substituted. 我希望$VAR被替换。

The lines I am matching are like: 我匹配的线条如下:

start ....some characters..... id: .....some characters..... [variable im searching for] ....some characters.... end start ....一些人物..... id: .....一些人物..... [variable im searching for] ....一些人物.... 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? 我知道我通常可以使用"$VAR"扩展变量,但这不会直接搜索正则表达式中的那些字符吗? 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. 此外,您可能希望使用$(grep ...)而不是反引号,因为它们是更现代的方法,并且具有更好的语法属性以及能够嵌套。

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.) (反斜杠在这里并不是绝对必要的,但我把它放进去给你一个想法。你的真实表达可能更复杂。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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