從多個文件輸出多個字串

從多個文件輸出多個字串

嗨我目前的程式碼是:

find /home/user/logfilesError/ -maxdepth 1 -type f -name "gBatch_*"\
 -daystart -mtime -1 -exec grep -rl "ERROR" "{}" +  | xargs -l  basename

if [ $? -eq 0 ]; then
    tday="$(date +'%d.%m.%Y')"
    echo "ERROR found on $tday in the files obove!"

else
    tday="$(date +'%d.%m.%Y')"
    echo "No ERROR was found at the $tday !"
fi

該程式碼目前輸出當天(不是最近 24 小時)創建或編輯的日誌文件,並蒐索日誌文件是否包含“錯誤”,並簡單地說明哪個日誌文件有錯誤,或者如果沒有任何錯誤,他也會這麼說。

我對名字進行了一些審查,所以不要認為我搞砸了,這就是它不起作用的原因;-)

輸出(範例):

gBatch_2070.log
gBatch_2071.log
ERROR found on 25.06.2014 in the files obove!

該資料夾看起來像:

資料夾

每個文件看起來像:

文件

我想要的輸出:

檔案名稱+“ERROR”+錯誤後的訊息

例子:

gBatch_2067.log - 錯誤 **.batch.BatchStart = Batchverarbeitung beeendet,gBatch_2077.log - 錯誤 **.batch.BatchStart = Batchverarbeitung beeendet,...

預先感謝您的幫忙!

答案1

這應該是您搜尋的內容:

find /home/user/logfilesError/ -maxdepth 1 -type f -name "gBatch_*" -daystart -mtime -1 \
-exec grep -H "ERROR" {} \; | sed -e 's/.*\/gBatch_/gBatch_/g' -e 's/:[^E]*/: /g' | tr '\n' ', '

範例輸出:

gBatch_2070.log:ERROR **.batch.BatchStart = Batchverarbeitung beeendet, gBatch_2077.log - ERROR **.batch.BatchStart = Batchverarbeitung beeendet
gBatch_2070.log:ERROR **.batch.BatchStart = Batchverarbeitung beeendet, gBatch_2077.log - ERROR **.batch.BatchStart = Batchverarbeitung beeendet
gBatch_2071.log:ERROR **.batch.BatchStart = Batchverarbeitung beeendet, gBatch_2077.log - ERROR **.batch.BatchStart = Batchverarbeitung beeendet
...

解釋:

  • -H也強制 grep 列印檔名
  • sed 's/.*\/gBatch_/gBatch_/g'將檔案名稱設為基本檔案名

答案2

find /home/user/logfilesError/ -maxdepth 1 -type f -name "gBatch_*"\
 -daystart -mtime -1 -exec grep -rl "ERROR" "{}" +  | xargs -l  basename\
 > /tmp/files_found

if [ $? -eq 0 ]; then
    tday="$(date +'%d.%m.%Y')"

    while read line
    do
       error=`grep "ERROR" /home/user/logfilesError/$line`
       error=`echo $error | sed 's/^.*ERROR/ERROR/' | tr '\n' ', '`
       echo "$line - $error"
    done < /tmp/files_found

    echo "ERROR found on $tday in the files obove!"
    rm /tmp/files_found

else
    tday="$(date +'%d.%m.%Y')"
    echo "No ERROR was found at the $tday !"
fi

相關內容