linux - 在 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
但没有用
解决方案
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
我们应该使用管道而不是使用它
推荐阅读
- batch-file - 使用限制 CPU 使用优化脚本命令 FFMPEG
- swift - 在 AKSequencer 中调用随机 AKPlayers 并重复随机结果
- powershell - 从 Windows 命令提示符执行 PowerShell 脚本
- c# - SQLBulkCopy 和事务
- java - 意图作为 int 发送到另一个活动的 ID 始终为零
- logging - 用less/tail动态改变grep
- angular - 如何创建嵌套的 formGroup 并在 Angular 中访问其属性
- algorithm - 将图节点分布到桶中
- r - 使用日期范围扩展 data.table,并处理其中一个日期为 NA 的情况
- javascript - 从 2 个值中获取数组索引