2013-02-12 90 views
4

我必须编写一个小的bash脚本来确定字符串是否对bash变量命名规则有效。我的脚本接受变量名称作为参数。我试图通过我的正则表达式将该参数传递给grep命令,但是我尝试了所有内容,grep尝试打开作为文件传递的值。将搜索字符串作为shell变量传递给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命令?

回答

7

这两个例子都将“$ 1”解释为文件名。要使用一个字符串,你可以使用

echo "$1" | grep "$regex" 

或特定的一个bash “这里字符串”

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 
+0

@chepner感谢您的编辑 – hek2mgl 2013-02-12 20:37:08

相关问题