2013-02-12 131 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

相關問題