在日期范围内创建的所有文件中进行 Grep [英] Grep inside all files created within date range

查看:31
本文介绍了在日期范围内创建的所有文件中进行 Grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ubuntu 操作系统.我想在 2012 年 5 月 28 日至 2012 年 5 月 30 日的日期范围内创建的所有日志文件中 grep 一个单词(比如 XYZ).

I am on the Ubuntu OS. I want to grep a word (say XYZ) inside all log files which are created within date range 28-may-2012 to 30-may-2012.

我该怎么做?

推荐答案

这与 Banthar 的解决方案有点不同,但它适用于不支持 find 版本-newermt 并展示了如何使用 xargs 命令,这是一个非常有用的工具.

This is a little different from Banthar's solution, but it will work with versions of find that don't support -newermt and it shows how to use the xargs command, which is a very useful tool.

您可以使用 find 命令来定位特定年龄"的文件.这将找到所有在 5 到 10 天前修改过的文件:

You can use the find command to locate files "of a certain age". This will find all files modified between 5 and 10 days ago:

 find /directory -type f -mtime -10 -mtime +5

然后在这些文件中搜索字符串:

To then search those files for a string:

 find /directory -type f -mtime -10 -mtime +5 -print0 |
   xargs -0 grep -l expression

您也可以使用 -exec 开关,但我发现 xargs 更具可读性(而且它通常也会执行得更好,但在这种情况下可能不是).

You can also use the -exec switch, but I find xargs more readable (and it will often perform better, too, but possibly not in this case).

(请注意,-0 标志可以让此命令对带有嵌入空格的文件进行操作,例如 this is my filename.)

(Note that the -0 flag is there to let this command operate on files with embedded spaces, such as this is my filename.)

评论中的问题更新

当您向 find 提供多个表达式时,它们会被与"在一起.例如,如果您要求:

When you provide multiple expressions to find, they are ANDed together. E.g., if you ask for:

find . -name foo -size +10k

...find 将仅返回 (a) 名为 foo (b) 大于 10 KB 的文件.同样,如果您指定:

...find will only return files that are both (a) named foo and (b) larger than 10 kbytes. Similarly, if you specify:

find . -mtime -10 -mtime +5

...find 只会返回 (a) 比 10 天前更新的文件 (b) 比 5 天前更早的文件.

...find will only return files that are (a) newer than 10 days ago and (b) older than 5 days ago.

例如,在我的系统上当前是:

For example, on my system it is currently:

$ date
Fri Aug 19 12:55:21 EDT 2016

我有以下文件:

$ ls -l
total 0
-rw-rw-r--. 1 lars lars 0 Aug 15 00:00 file1
-rw-rw-r--. 1 lars lars 0 Aug 10 00:00 file2
-rw-rw-r--. 1 lars lars 0 Aug  5 00:00 file3

如果我要求超过 5 天前修改的文件 (-mtime +5) 我得到:

If I ask for "files modified more than 5 days ago (-mtime +5) I get:

$ find . -mtime +5
./file3
./file2

但如果我要求修改时间超过 5 天但不到 10 天的文件"(-mtime +5 -mtime -10),我会得到:

But if I ask for "files modified more than 5 days ago but less than 10 days ago" (-mtime +5 -mtime -10), I get:

$ find . -mtime +5 -mtime -10
./file2

这篇关于在日期范围内创建的所有文件中进行 Grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆