首页 > 解决方案 > 使用 bash 计算字符串的出现次数

问题描述

我需要使用 bash 计算日志文件中字符串的出现次数,并在字符串重复超过 5 次后执行命令。

我有来自日志文件的以下示例数据:

[10:35:56] world_log_event: kick (starrr)(NormieBL)@Arca from srv 192.168.1.6(21)  
[10:39:17] world_log_data: user (chrisxJ02)(Delaon)@Arca is already connected on srv 7
[10:39:23] world_log_event: kick (chrisxJ02)(Delaon)@Arca from srv 192.168.1.39(7)
[10:39:17] world_log_data: user (test01)(testDW)@Arca is already connected on srv 39

脚本应如何表现的一些示例:

if string "is already connected on srv 21" count is =>5 times then "exec command telnet 192.168.1.6"
if string "is already connected on srv 7" count is =>5 times then "exec command telnet 192.168.1.39"

标签: bashshellsh

解决方案


计算出现次数的一种简单方法是使用grep -c 'string' file. 因此,在您的情况下,您可以在复合命令中使用命令替换并执行以下操作:

[ "$(grep -c 'Lorem ipsum dolor sit amet 21' f)" -gt 5 ] && 
echo "execute cmd" || 
echo "no cmd"

上面检查是否"Lorem ipsum dolor sit amet 21"发生-gt(大于)5次,如果是,那么echo "execute cmd"或如果不是echo "no cmd"。如果你愿意,你可以把它做成一个if ... then ... else ... fi表格。

注意:表单[ test ] && do this || do that不是真正的替代品,if ... then ... else ... fi因为如果测试为真且do this失败,do that则将被执行。但是在 where do thisis的情况下echo "...",这并不是真正的问题)

示例使用/输出

通过您在 file 中的输入f,您将拥有:

$ [ "$(grep -c 'Lorem ipsum dolor sit amet 21' f)" -gt 5 ] &&
> echo "execute cmd" ||
> echo "no cmd"
execute cmd

推荐阅读