簡體   English   中英

如何只重復最近匹配的搜索字符串?

[英]How to grep only the recently matched search string?

我有一個日志文件,它每秒更新一次。 grep '一些字符串,並將搜索結果拉到一個臨時文件。 然后,我將該臨時文件結果發送到我的電子郵件中。 我正在cron運行此腳本。 但是,當cron再次觸發腳本並且腳本捕獲了新搜索的字符串時,它在臨時文件中也為我提供了先前/舊的結果。

例如,我的日志文件如下所示,但不完全相同:

2018-02-15 14:36:47,344 INFO : Bread butter jam

2018-02-15 14:37:22,566 INFO : trees

2018-02-15 14:37:22,636 INFO : fruits

2018-02-15 14:37:22,636 INFO : veggies

2018-02-15 14:37:22,745 INFO : junkies

2018-02-15 14:37:23,648 INFO : Bread butter jam

2018-02-15 14:37:23,659 INFO : cakes

2018-02-15 14:37:23,734 INFO : cookies

2018-02-15 14:37:23,767 INFO : meat

2018-02-15 14:37:23,874 INFO : yogurt

我希望面包黃油果醬每次出現在日志文件中時都存儲在一個臨時文件中。

如何僅將新搜索的結果提取到臨時文件?

對不起,我的英語不好,我是bash的新手。

如注釋中所述,您應該將當前日志大小與上一個要存儲在文件中的日志大小進行比較。

這樣的事情應該可以解決問題:

#!/bin/bash
CURRENT_LINECOUNT=$(cat /path/to/LogFile | wc - l)
#redirection is here in case the old_count file doesn't exist
OLD_LINECOUNT=$(cat /path/to/old_count 2>/dev/null)

tail -n $((CURRENT_LINECOUNT - ${OLD_LINECOUNT:-0})) /path/to/LogFile | grep "Bread butter jam" > /path/to/temp/file
echo $CURRENT_LINECOUNT > /path/to/old_count

#here, your logic to send the temp file

如果日志文件足夠小,可以每分鍾grepping字符串,則可以使用以下事實:新行將具有不同的時間戳。 就像是

mytmp=/tmp/breakfast.tmp
mylasttmp=/tmp/breakfast.lasttmp
myattachment=/tmp/breakfast.now
test -f ${mytmp} && { echo "Last cron processing still running"; exit 1;}
touch ${mytmp}

grep -E "Bread butter jam" logfile > ${mytmp}

comm -3 ${mytmp} ${mylasttmp} > ${myattachment}
# process ${myattachment} and when that is finished...
mv ${myattachment} ${mylasttmp}
rm ${mytmp}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM