bash grep正则表达式中的shell变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18147884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:02:18  来源:igfitidea点击:

shell variable in a grep regex

bashgrep

提问by mike_b

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.

我正在尝试在 grep 正则表达式中使用变量。我只会发布一个失败的例子,也许有人可以建议如何在运行 grep 命令时评估变量。我也试过${var}了。

$ 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.

由于我的正则表达式应该匹配以“test”开头的行,它应该打印通过它回显的行。

$ echo $string
test this
$

回答by David W.

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 quotea $if you're using double quotes.

您需要使用双引号。单引号可防止 shell 变量被 shell 插入。您使用单引号来防止 shell 进行插值,如果您的正则表达式用作$模式的一部分,您可能必须这样做。如果您使用双引号,您也可以使用反斜杠来引用a $

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

此外,您可能需要将变量放在花括号${var}中,以帮助将其与模式的其余部分分开。

Example:

例子:

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