首页 > 解决方案 > 在 Linux 中查找、grep 和 wc

问题描述

我想首先 grep 在 DateTime 范围内创建的日志文件中的一些文本,然后输出该文本的出现次数。我已经设法找出 Unix 命令来查找日期范围内的文件并 grep 查找这些文件中的文本。但是,我无法找到一种方法来找到该文本的出现次数

find . -maxdepth 1 -newermt "2021-10-06 02:06:00" ! -newermt "2021-10-06 06:30:00" | xargs grep "text"  

最后尝试使用xargs wc -l但没有用

标签: linuxunix

解决方案


xargs如果要计算出现次数,则不需要最后使用,只需将其通过管道传输到wc -l.

截屏

root@HOST:/var/log/apache2# find . -maxdepth 1 -type f -newermt "2021-10-06 02:06:00" ! -newermt "2021-10-06 06:30:00"
./error.log
./error.log.1
root@HOST:/var/log/apache2# find . -maxdepth 1 -type f -newermt "2021-10-06 02:06:00" ! -newermt "2021-10-06 06:30:00" | xargs grep "Apache"
./error.log:[Wed Oct 06 06:25:11.574179 2021] [mpm_prefork:notice] [pid 4138] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1j configured -- resuming normal operations
./error.log.1:[Tue Oct 05 06:25:09.859586 2021] [mpm_prefork:notice] [pid 4138] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1j configured -- resuming normal operations
root@HOST:/var/log/apache2# find . -maxdepth 1 -type f -newermt "2021-10-06 02:06:00" ! -newermt "2021-10-06 06:30:00" | xargs grep "Apache" | wc -l
2
root@HOST:/var/log/apache2#

这是你的出现次数:2

解释:

  • xargs 读取先前命令的输出,然后用它构建下一个命令
  • 上一个命令的输出是:
./error.log:[Wed Oct 06 06:25:11.574179 2021] [mpm_prefork:notice] [pid 4138] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1j configured -- resuming normal operations
./error.log.1:[Tue Oct 05 06:25:09.859586 2021] [mpm_prefork:notice] [pid 4138] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1j configured -- resuming normal operations
  • 所以结果find . -maxdepth 1 -type f -newermt "2021-10-06 02:06:00" ! -newermt "2021-10-06 06:30:00" | xargs grep "Apache" | xargs wc -l就像调用:wc -l (output of previous command here)
  • 但这不是我们想要的(尝试手动调用),我们想要的wc -l < (output of previous command here)是:我们将前一个命令的输出传递给 wc 的 STDIN
  • 所以,xargs我们应该使用管道而不是使用它

推荐阅读