bash 将搜索字符串作为 shell 变量传递给 grep

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14841032/
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-18 04:32:39  来源:igfitidea点击:

passing search string to grep as a shell variable

bashgrep

提问by user1222073

I have to write a small bash script that determines if a string is valid for the bash variable naming rules. My script accepts the variable name as an argument. I am trying to pass that argument to the grep command with my regex but everything I tried, grep tries to open the value passed as a file.

我必须编写一个小的 bash 脚本来确定字符串对于 bash 变量命名规则是否有效。我的脚本接受变量名作为参数。我试图用我的正则表达式将该参数传递给 grep 命令,但我尝试过的一切,grep 尝试打开作为文件传递的值。

I tried placing it after the command as such
grep "$regex" ""

and also tried passing it as redirected input, both with and without quotes
grep "$regex" <""

and both times grep tries to open it as a file. Is there a way to pass a variable to the grep command?

并且两次 grep 都尝试将其作为文件打开。有没有办法将变量传递给 grep 命令?

回答by that other guy

Both your examples interpret "$1" as a filename. To use a string, you can use

您的两个示例都将 "$1" 解释为文件名。要使用字符串,您可以使用

echo "" | grep "$regex" 

or a bash specific "here string"

或 bash 特定的“此处字符串”

grep "$regex" <<< ""

You can also do it faster without grep with

你也可以在没有 grep 的情况下更快地完成

[[  =~ $regex ]]  # regex syntax may not be the same as grep's

or if you're just checking for a substring,

或者如果你只是检查一个子字符串,

[[  == *someword* ]]

回答by hek2mgl

You can use the bash builtin feature =~. Like this:

您可以使用 bash 内置功能=~。像这样:

if [[ "$string" =~ $regex ]] ; then 
    echo "match"
else 
    echo "dont match"
fi