尝试了其他解决方案,但未给出正确的解决方案,我的时间格式为[2020年8月20日星期四09:28:51]。最接近的一个是这个
awk -vDate=`date -d'now-2 hours' +[%a %b %d %H:%M:%S %Y]` '$4 > Date {print Date, $0}' $input
我的日志文件是这样的
[Thu Aug 20 09:10:51 2020] [error] vendor
[Thu Aug 20 09:23:51 2020] [error] vendor
[Thu Aug 20 09:25:51 2020] [error] vendor
[Thu Aug 20 09:27:51 2020] [error] vendor
[Thu Aug 20 09:28:51 2020] [error] dad
我想要从当前时间[2020年8月20日星期四09:28:51]到最后10分钟的结果
[Thu Aug 20 09:23:51 2020] [error] vendor
[Thu Aug 20 09:25:51 2020] [error] vendor
[Thu Aug 20 09:27:51 2020] [error] vendor
[Thu Aug 20 09:28:51 2020] [error] dad
答案 0 :(得分:0)
好吧,我尝试直接使用grep进行操作,但是我不知道为什么,但是grep没有采用这种日期格式并给出了错误的输出,因此我为此采取了一些措施。
#!/bin/bash
input="/home/babin/Desktop/code2"
count=0
dateyear=$(date +'%Y')
month=$(date +'%b')
day=$(date +'%a')
#do loop for 10 mins from now
for (( i = 0; i <=9; i++ )) ; do
if grep $(date +%R -d "-$i min") $input | grep -i "error" | grep -wi "$month" | grep -wi "$year" | grep -wi "$day"
then
currentcount=$(grep $(date +%R -d "-$i min") $input | grep -wi "70007" | grep -wi "$month" | grep -wi "$year" | grep -wic "$day")
else
currentcount=0
echo "not found"
fi
count=$(( $count + $currentcount ))
done
echo "$count"
#check no of error found and do task
if(( $count >= 10))
then
echo "more oe equal to 10 finds"
else
echo "less than 10 occurence"
fi
它给出输出,因为当前时间是[Thu Aug 20 09:28:51 2020]并且它匹配“错误”字符串。
enter [Thu Aug 20 09:23:51 2020] [error] vendor
[Thu Aug 20 09:25:51 2020] [error] vendor
[Thu Aug 20 09:27:51 2020] [error] vendor
[Thu Aug 20 09:28:51 2020] [error] dadcode here
答案 1 :(得分:0)
总体流程为:
总体而言,请使用流在bash中工作。 strptime
来自dateutils
软件包。像这样:
# Extract the date+time part from within [..] and put it on the first column with tab
sed 's/ \[\([^]]*\)\]/\1\t&/' "$input" |
# For each line
while IFS=$'\t' read -r date rest; do
# Convert the date to seconds since epoch
date=$(strptime -f "%s" -i "%a %b %d %H:%M:%S %Y" "$date")
# Output the updated line
printf "%s\t%s\n" "$date" "$rest"
done |
# Read it all in awk and compare second since epoch in the first field to given value
awk -v "since=$(date -d'now -2 hours' +%s)" '$1 > since' |
# Remove first field - ie. second since epoch
cut -f2-
请勿使用反引号``。 They are discouraged。请改用$(...)
。切记要引用所有变量扩展。使用http://shellcheck.net检查脚本中最常见的错误。我认为在date
和strptime
之间的某个地方,您的时区可能会遇到问题(即小时数差异)。