2 つのログ日付間の sed コマンド

2 つのログ日付間の sed コマンド

私は "error"という単語を含む昨日と今日の間のログファイルだけを見て存在する場合、単純なY / Nを返すために次のsed行を作成しました。

私は実際に私に必要な適切な収益を提供していません。誰かが私が何が間違っているかを指摘するのに役立ちますか?

 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;
)"

ベストアンサー1

ここでは構文が間違っています。

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 -cそれを使用して常に数値を返し、一致するものがない場合は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) "

おすすめ記事