0

Currently, I use this version of grep -rlw

grep -rlw . -e "string_to_search"

To search for overall files containing "string_to_search".

I want to modify it to find files that are not older than 7 days.

How do I do it?

grep -rlw . -e "string_to_search" | find -mtime +7|print

Would something like this work?

1 Answers1

2

You'd need to use either find or zsh to find the files based on age to pass to grep.

  • find:

    find . -mtime -7 -type f -exec grep -lFw string_to_search {} +
    
  • zsh:

    grep -lFw -- string_to_search **/*(D.m-7)
    

Using zsh avoids the ./ prefix added to file paths and give you a sorted list but means we need the -- (for non-POSIX greps such as GNU grep or compatible) to guard against file paths that start with -. The zsh approach could hit the system's execve() limit on the size of arguments+environments which can be worked around using the zargs autoloadable function.

With the GNU implementations of find, sort and xargs, you can also avoid the ./ prefix and sort the list with:

find . -mtime -7 -type f -printf '%P\0' |
  sort -z |
  xargs -r0 grep -lFw -- string_to_search

-mtime -7 and m-7 match on files whose age (based on mtime) rounded down to an integer number of days (a day in this case being a duration of 86400 Unix seconds) is strictly less than 7. So that would be typically those last modified since same time same day last week (or in the future) except when there's been a DST change in the interval.

-mtime +7 would be for ages strictly greater than 7, so for files 8 days (8 * 86400 seconds) old or older.