繁体   English   中英

找到,grep然后wc在Linux

[英]Find, grep and then wc in Linux

我想首先 grep 在日期时间范围内创建的日志文件中的一些文本,然后 output 该文本的出现次数。 我已经设法找出 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 ,只需将它 pipe 到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 读取之前命令的 output,然后用它构建下一个命令
  • 上一个命令的 output 是:
./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 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 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) ,即:我们将 output of previous command 传递给 wc 的 STDIN
  • 所以,不使用xargs ,我们应该只使用 pipe 它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM