Grep inside all files created within date range

前端 未结 3 701
我在风中等你
我在风中等你 2020-12-03 00:54

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.

How do I do that?

相关标签:
3条回答
  • 2020-12-03 01:33

    find doesn't seem to have options where you can specify specific dates for timestamp comparison (at least the version on my laptop doesn't - there may be other versions and/or other tools that perform similarly), so you'll have to use the number of days. So, as of 2012/06/05, you want to find files newer than 9 days but older than 6 days:

    find . -type f -ctime -9 -ctime +6 -print0 | xargs -0 grep XYZ
    
    0 讨论(0)
  • 2020-12-03 01:35

    Combine grep with find:

    find -newermt "28 May 2012" -not -newermt "30 May 2012" -exec grep XYZ \{\} \;
    
    0 讨论(0)
  • 2020-12-03 01:36

    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.

    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
    

    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).

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

    Update for question in comments

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

    find . -name foo -size +10k
    

    ...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 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
    

    I have the following files:

    $ 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
    

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

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

    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
    
    0 讨论(0)
提交回复
热议问题