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

4

我需要编写一个小的bash脚本来确定一个字符串是否符合bash变量命名规则。我的脚本接受变量名作为参数。我试图将该参数与我的正则表达式一起传递给grep命令,但是无论我尝试了什么,grep都会尝试打开传递的值作为文件。

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

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

每次grep都会尝试将其作为文件打开,有没有办法将变量传递给grep命令?

2个回答

8

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

echo "$1" | grep "$regex" 

或者使用特定于bash的“here string”。
grep "$regex" <<< "$1"

您可以不使用grep更快地完成这个操作:
[[ $1 =~ $regex ]]  # regex syntax may not be the same as grep's

如果您只是检查子字符串,

[[ $1 == *someword* ]]

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接