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

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

问题描述

我想在grep的正则表达式使用变量。我只是张贴失败的例子,也许有人可以建议如何使变量进行评估,运行grep命令时。我试过 $ {VAR} 以及

  $字符串=此测试
是$ var =测试
$回声$字符串| grep'可以^ $ VAR
$

由于我的正则表达式应该匹配它以test开头的行,它应该打印线呼应THRU它。

  $回声$字符串
这个测试
$


解决方案

您需要用双引号。单引号prevent从外壳进行插值shell变量。您可以使用单引号prevent从做插值外壳,你可能有,如果你的常规的前pression使用 $ 作为模式的一部分来做。您还可以使用反斜杠的报价的一个 $ 如果你使用双引号。

此外,您可能需要把你的变量在大括号 $ {VAR} ,以帮助它从图案的其余部分分开。

例如:

  $字符串=此测试
是$ var =测试
$回声$字符串| 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'
$ 

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

$ echo $string
test this
$

解决方案

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.

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

Example:

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

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

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