2015-11-04 275 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条件使用:它是有效的,因为它会成功退出,当它发现第一比赛 - 它不具有读取文件的其余部分。

相关问题