2010-10-08 47 views
0

我想在unix中運行一個腳本,它將在傳遞的參數中查找特定的模式。在所有情況下,論點都是一個單詞。我不能使用grep,因爲grep只能用於搜索文件。有沒有更好的unix命令可以幫助我?如何在UNIX中的單個單詞上使用grep?

回答

5

grep的可以儘管文件中搜索,也可以在標準輸入工作:

 
$ echo "this is a test" | grep is 
this is a test 
2

根據什麼你在做你可能更喜歡使用bash模式匹配:

# Look for text in $word 
if [[ $word == *text* ]] 
then 
    echo "Match"; 
fi 

或正則表達式:

# Check is $regex matches $word 
if [[ $word =~ $regex ]] 
then 
    echo "Match"; 
fi 
1

您也可以使用case/esac。無需調用任何外部命令(你的情況)

case "$argument" in 
    *text*) echo "found";; 
esac 
0
if echo $argument | grep -q pattern 
then 
    echo "Matched" 
fi 
0

我的文件是:

$ cat > log 
loga 

hai how are you loga 

hai 

hello 

loga 

我的命令是:

sed -n '/loga/p' log 

我的回答是:

loga 

hai how are you loga 

loga 
相關問題