[英]use grep/sed/awk to extract string corresponding to certain field
[英]How to use awk/sed/grep to filter out only the latest string in a real-time log file
這件事真的讓我感到困惑。 假設我有一個像這樣的文件
09:35:24 03/04/2014 Pink Floyd the best band in the world KING KING
09:44:21 03/04/2014 Led Zeppelin the greatest hard rock band ever
09:54:21 03/04/2014 Bon scott I love Bon scott KING KING
10:15:23 03/04/2014 AC/DC is the best
10:35:43 03/04/2014 It's all a joke
12:46:55 03/04/2014 No value nothing is there here KING KING
15:35:43 03/04/2014 It's all a joke1
15:39:43 03/04/2014 It's all a joker KING KING
15:55:43 03/04/2014 It's all a jokeeyyyy
現在,上面的文件是一個文件,該文件將在早上創建,並一直追加到午夜。 現在,我必須提取模式KING KING存在的行。 我的是一個監視腳本,因此它每60秒檢查一次該文件是否為KING KING模式,如果存在,我將其放在新文件中以進行進一步操作。 現在,如果您看到時間戳是不同的,則在10:15,我得到了前兩行具有匹配模式的行。 現在在12:46運行腳本時,我不再想要以前找到的匹配模式,即在12:46我只想要"12:46:55 03/04/2014 No value nothing is there here KING KING "
而不是09:54和09:35的值(我是Bon scott和Pink Floyd),因此基本上,我該如何使用grep / sed / awk僅過濾最新的值,而不給我舊的值。 謝謝。
編輯:
在10:00,我的腳本運行KING KING的grep,並獲得Pink Floyd和Bon Scott的台詞。 現在再說一次(比如說)16:00我的腳本運行了,我只想要字符串
12:46:55 03/04/2014 No value nothing is there here KING KING
和
15:39:43 03/04/2014 It's all a joker KING KING
而不是較老的。 請注意,不僅2,而且可能有很多KING KING模式。
grep "KING KING" <your file> | tail -n 1
您說您只想要包含KING KING的最新行。 您可以使用tail -n 1來抓取最后一個,這是最新的一個,前提是您的文件追加而不是添加行。
如果准備好了,您可以改用head
。
編輯:
如果您想查看原始日志更新中可能出現的潛在新KING KING行,則可以在此處使用tail -f
。
否則,如果您只想要最新的,但又想更新,則將不得不不斷地對其進行輪詢。
例:
while true
do
grep "KING KING" <your file> | grep -vf <your temporary file>
grep "KING KING" <your file> > <your temporary file>
sleep 2
done
那只是我的頭上。 它可能需要一些調整,但我現在無法訪問終端。 另外,您不需要每次都重寫臨時文件,並且可以使用cat
追加到臨時文件的末尾,但是我將留給您使用,以解決該問題。 :)
您可以將一個臨時文件保存在當天的先前比賽中:
touch matches.txt
grep "KING KING" output.log | grep -vFf matches.txt | tee -a matches.txt
這將過濾掉matches.txt
中存儲的所有先前匹配項,並將新匹配項追加到該文件。 您可能需要在午夜將其清空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.