Bash 保留截断文件中出现的次数

Bash 保留截断文件中出现的次数,bash,grep,counter,cat,wc,Bash,Grep,Counter,Cat,Wc,假设我有一个名为data.log的文件 数据不断地被附加到其中,其中可能包含“flag”,并被外部脚本截断: [13/Jan/2015:11:11:53+0000]库拉比图尔旗拉齐尼亚尼布(lacinia nibh)在封建的摩利斯 tail:data.log:文件被截断 [13/Jan/2015:11:11:53+0000]dapibus enim Sagitti功效 [13/Jan/2015:11:11:54+0000]iaculis non旗帜 声明counter=0后,我想用找到的次数增加

假设我有一个名为data.log的文件

数据不断地被附加到其中,其中可能包含“flag”,并被外部脚本截断:

[13/Jan/2015:11:11:53+0000]库拉比图尔拉齐尼亚尼布(lacinia nibh)在封建的摩利斯

tail:data.log:文件被截断

[13/Jan/2015:11:11:53+0000]dapibus enim Sagitti功效

[13/Jan/2015:11:11:54+0000]iaculis non旗帜

声明
counter=0
后,我想用找到的次数增加它。我想出了类似的方法,它使用
wc-l
来计算data.log中包含“flag”的行数:


现在只剩下一个问题:截断。我将如何处理这个问题?我想做一个,但是我怎么才能理解截断事件呢?或者我还有其他的方向吗?

这对你来说应该很有用:

$ tail -F data.log | grep --line-buffered s | while read match ; do ((counter++)) ; done
tail
-F
标志与
--跟随--重试
相同<代码>--重试是这里的神奇之处:

   --retry
          keep trying to open a file even when it is or becomes inaccessi‐
          ble; useful when following by name, i.e., with --follow=name
我还使用了
--行缓冲
grep
,以避免while循环需要等待输出


我刚刚意识到的一个问题是:如果每行的标志出现不止一次,
$counter
仍然只会增加1。但是这个问题也存在于您的解决方案中。

另外,
$(cat data.log)
完全可以在
bash
中完成,因为:
$(
更有效。另外,
counter=$($counter+3))
可以写成:
((counter+=3))
(这在我看来更容易阅读)。太棒了。很好的解决方案,看起来也不错。谢谢!
   --retry
          keep trying to open a file even when it is or becomes inaccessi‐
          ble; useful when following by name, i.e., with --follow=name