【问题标题】:Shell script to execute grep with time and provide the output in a file随时间执行 grep 并在文件中提供输出的 Shell 脚本
【发布时间】:2017-04-25 13:24:10
【问题描述】:

我想写一个脚本来执行命令

cat file.txt | grep -c 'HH:MM' [此处 HH:MM 为 00:00 至 23:59] 以及想要以某种格式保存在文件中的任何输出 00:00 - 2134 00:01 - 3127 . . . . 23:59 - 1298

提前致谢。

【问题讨论】:

  • 你的问题是什么?
  • 类似grep -Eo "[0-2][0-9]:[0-5][0-9]" | sort | uniq -c ?
  • 我的服务器中有一个文件,其中请求来自移动设备并且数量很大(例如每分钟超过 100 个请求)。我想获得请求的计数,以便我可以计算出请求高的时间。所以当我执行cat file.txt | grep -c '10:30' 时,它会在 10:30 给出消息计数。同样会得到 00:00, 00:01, 00:02 ..... ..... ...23:59。
  • 流过的消息还包括IP、描述和时间。这就是为什么我想随着时间的推移过滤掉。并希望将所有计数存储在由脚本相对于时间创建的单独文件中。例如 00:00 - 计数 a,00:01 - 计数 b,像这样。希望这个解释有一些清晰的观点
  • 我得到了解决方案。谢谢@WalterA。您的命令行在一些修改后工作

标签: linux bash shell


【解决方案1】:

在 grep 命令中添加文件名时,可以避免额外的命令 cat
当 access.log 已经按日期排序时,可以跳过排序。

grep -Eo "2017-04-25T[0-2][0-9]:[0-5][0-9]" /local/logs/access.log | uniq -c > /tmp/list.txt

使用 access.log,您必须知道有人可以通过尝试访问网页 http://yoursite/2017-04-25T11:11/fooledyou.html
来“攻击”您的脚本(使统计信息失败) 您可以使用sed 来更好地控制您选择子字符串的方式

# test remove from start of line until the first [ and also remove the [,
# remember the matched date and remove the rest, replace by remembered string.
echo "127.0.0.1 - - [2017-04-25T11:11 +0000] GET /2017-04-25T22:22/fooledyou.html HTTP/1.1 200 140 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" |
   sed 's/[^\[]*\[\(2017-04-25T[0-2][0-9]:[0-5][0-9]\).*/\1/'

# your command
sed 's/[^\[]*\[\(2017-04-25T[0-2][0-9]:[0-5][0-9]\).*/\1/' /local/logs/access.log |
   uniq -c > /tmp/list.txt

【讨论】:

    【解决方案2】:

    脚本只有一行。

    #!/bin/bash
    cat /local/logs/access.log | grep -Eo "2017-04-25T[0-2][0-9]:[0-5][0-9]" | sort | uniq -c > /tmp/list.txt
    

    执行后我得到一个文件list.txt,当我打开它时,得到如下所述的列表。

    Output of the script

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多