Bash

兩個日誌日期之間的 sed 命令

  • October 27, 2022

我編寫了以下 sed 行,試圖僅查看昨天和今天之間包含“錯誤”一詞的日誌文件,如果它們在那裡,則返回簡單的 Y / N。

我實際上並沒有給我我需要的適當回報。有人可以幫我指出哪裡出了問題嗎?

today="$(date +%Y-%m-%d)"
yesterday="$(date -d '24 hour ago' +%Y-%m-%d)"
   iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" /mnt/data/systemlogs/logstash/logs/pipeline.log | grep "ERROR" ] = ""  ; then
   echo "No"
else
   echo "Yes"
fi;
)"

您的語法在這裡是錯誤的:

iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR" ] = ""  ; then
   echo "No"
else
   echo "Yes"
fi;
)"

構造的語法if [ ]if [ condition ]. 你有if [ command ] condition因為在= ""外面[ ]。執行該程式碼應該會給您一些語法錯誤:

$ iserror="$(if [ sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR" ] = ""  ; then
    echo "No"
 else
    echo "Yes"
 fi;
)"
bash: [: missing `]'
grep: ]: No such file or directory
grep: =: No such file or directory
grep: : No such file or directory

您正在嘗試的是:

iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "ERROR") = "" ] ; then
   echo "No"
else
   echo "Yes"
fi;
)"

但這也不好,因為如果沒有grep返回任何內容,您將失去一個參數並得到一個不同的錯誤:

$ iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep "bERROR") = "" ] ; then
   echo "No"
else
   echo "Yes"
fi;
)"
bash: [: =: unary operator expected

相反,您可以使用grep -cwhich 將始終返回一個數字,如果沒有匹配則返回 0,如果有匹配則返回:

iserror="$(if [ $(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | grep -c "ERROR") -eq 0 ] ; then
   echo "No"
else
   echo "Yes"
fi;
)"

或者,更簡單的是,使用grep -q它不產生輸出,但如果找到某些東西則成功退出,如果沒有則失敗:

iserror="$(sed -n "/"$yesterday"/,/"$today"/p" pipeline.log | 
       grep -q "ERROR" && 
           echo Yes || 
               echo No)"

順便說一句,您還可以更多地使用此處,並且僅在相關行中sed有匹配項時才列印:ERROR

iserror="$(if [ $(sed -n '/2022-10-26/,/2022-10-27/{ /ERROR/p }' pipeline.log | wc -l) -gt 0 ]; then 
   echo Yes; 
else 
   echo No; 
fi) "

引用自:https://unix.stackexchange.com/questions/722675