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 命令?

4

2 回答 2

8

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

echo "$1" | grep "$regex" 

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

grep "$regex" <<< "$1"

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

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

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

[[ $1 == *someword* ]]
于 2013-02-12T20:20:55.480 回答
0

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

if [[ "$string" =~ $regex ]] ; then 
    echo "match"
else 
    echo "dont match"
fi
于 2013-02-12T20:21:11.197 回答