bash - 使用 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"
解决方案
计算出现次数的一种简单方法是使用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 this
is的情况下echo "..."
,这并不是真正的问题)
示例使用/输出
通过您在 file 中的输入f
,您将拥有:
$ [ "$(grep -c 'Lorem ipsum dolor sit amet 21' f)" -gt 5 ] &&
> echo "execute cmd" ||
> echo "no cmd"
execute cmd
推荐阅读
- python - lxml 在 bs4 中未被识别:Mac 上的 Python 3
- asp.net - 验证 html5 两个提交按钮 .net
- android - 如何在 react-native 中缩小 WebView?
- javascript - 将图像设置为页面在 React 中呈现的第一张图像
- sas - 手动和由 SAS 完成时的卡方检验结果差异
- reactjs - 模拟 textarea Jest 测试的更改
- opengl - 将递归渲染的场景显示到平面中
- sql - 数据类型等效项:MS Access 表 ↔ 'CREATE TABLE' 查询 ↔ ODBC SQL
- java - 使用 switch 语句设置对象变量
- vb.net - 作为图形对象的球和曲线之间的碰撞