Grep inside all files created within date range
date-range, find, grep, linux, ubuntu
Solution
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
Problem
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?