2015-11-04 262 views
1

我有一個優化我的bash腳本的問題。我有幾個模式需要在日誌文件中查找。如果其中一個模式在日誌文件中列出,則執行SOMETHING。到目前爲止,我有這個,但我怎麼能優化它沒有這麼多的變數:如何使用bash腳本在日誌文件中搜索多個字符串

search_trace() { 
    TYPE=$1 
    for i in `find ${LOGTRC}/* -prune -type f -name "${USER}${TYPE}*" ` 
    do 
      res1=0 
      res1=`grep -c "String1" $i`     
      res2=0 
      res2=`grep -c "String2" $i`     
      res3=0 
      res3=`grep -c "String3" $i`     
      res4=0 
      res4=`grep -c "String4" $i` 
      if [ $res1 -gt 0 ] || [ $res2 -gt 0 ] || [ $res3 -gt 0 ] || [ $res4 -gt 0 ]; then 
        write_log W "Something is done ,because of connection reset in ${i}" 
        sleep 5 
      fi 
    done 

回答

1

你可以簡單地使用alternation語法正則表達式傳遞給grep,例如

if grep -q -E '(String1|String2|String3|String4) filename'; then 
    # do something 
fi 

-E該選項使得grep的使用extended regular expressions(包括交替(|)運算符)。

0
search_trace() { 
    find "$LOGTRC"/* -prune -type f -name "$USER${1}*" | 
    while IFS= read -r filename; do 
     if grep -q -e String1 -e String2 -e String3 -e String4 "$filename"; then 
      write_log W "Something is done ,because of connection reset in $filename" 
      sleep 5 
     fi 
    done 
} 

的grep的-q選項適用於在if條件使用:它是有效的,因爲它會成功退出,當它發現第一比賽 - 它不具有讀取文件的其餘部分。

相關問題