grep正则表达式中的shell变量 [英] shell variable in a grep regex

查看:88
本文介绍了grep正则表达式中的shell变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Since my regex should match lines which start with "test", it should print the line echoed thru it.

$ echo $string
test this
$

推荐答案

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

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.

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

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

示例:

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

这篇关于grep正则表达式中的shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆