如何使用bash脚本在日志文件中搜索多个字符串

时间:2015-11-04 15:52:55

标签: bash

我在优化我的bash脚本时遇到了问题。我需要在日志文件中查找几个模式。如果其中一个模式列在日志文件中,则执行SOMETHING。到目前为止,我有这个,但可以,如何在没有这么多变量的情况下对其进行优化:

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

2 个答案:

答案 0 :(得分:1)

您可以在传递给mydt[, grep("_0$", names(mydt), value=T) := NULL] mydt # id x_1 x_2 x_3 y_1 y_2 y_3 new_col #1: 1 2 3 NA 5 4 NA 7 #2: 2 4 5 6 3 2 1 NA #3: 3 NA NA NA NA NA NA 0 的正则表达式中使用alternation语法,例如

grep

if grep -q -E '(String1|String2|String3|String4) filename'; then # do something fi 选项使grep使用extended regular expressions(包括替换(-E)运算符)。

答案 1 :(得分: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条件中使用:它很有效,因为它会在找到第一个匹配时成功退出 - 它不会&# 39; t必须阅读文件的其余部分。

相关问题