2010-03-13 105 views

回答

4

如果您需要執行對包含文本的所有文件的命令,你可以用xargs結合grep 。例如,這將刪除含有「yourtext」所有文件:

grep -l "yourtext" * | xargs rm 

要搜索一個文件,使用if grep ...

if grep -q "yourtext" yourfile ; then 
    # Found 
fi 
2

像下面會做你的需要。

grep -w "text" file > /dev/null 

if [ $? -eq 0 ]; then 
    #Do something 
else 
    #Do something else 
fi 
+1

我更喜歡'如果[$(grep的-c 「文本」 文件)-gt 0]',但它同樣的事情。 – 2010-03-13 18:41:19

+1

馬丁的方法(使用'grep -q')比這兩種方法都更快(不搜索整個文件,只是第一次匹配)和(恕我直言)清潔。 – 2010-03-13 20:25:20

1

你可以把grepif語句中,你可以使用-q標誌使其沉默。

if grep -q "text" file; then 
    : 
else 
    : 
fi 
0

只是使用shell

while read -r line 
do 
    case "$line" in 
    *text*) 
     echo "do something here" 
     ;; 
    *) echo "text not found" 
    esac 
done <"file" 
相關問題