You'd need to use either find
or zsh
to find the files based on age to pass to grep
.
Using zsh
avoids the ./
prefix added to file paths and give you a sorted list but means we need the --
(for non-POSIX grep
s 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.
find . -mtime -15 -name "*.gz" -exec zgrep -lH "string_to_search" {} \;
/ Should I delete the question? – achhainsan Oct 04 '23 at 07:417
in the question and use15
in the comment with what you claim to be a solution? Also the solution contains clauses that search for and work with gzipped files, the question didn't mention that. I would probably have done something likefind . -mtime -7 | xargs grep -lw "string_to_search_for"
. – Henrik supports the community Oct 04 '23 at 08:51find -exec
is better thanfind | xargs
in that it works with ugly filenames too (xargs
by default processes e.g. spaces and quotes specially, not just newlines). Go withfind -exec grep ... {} +
to run a single grep for many files – ilkkachu Oct 04 '23 at 09:05find
didn't have the-exec ... +
syntax when I first learned of it, so I've never gotten used to it, if I need to handle ugly filenames I usually makefind
null-terminate the names (with-print0
) and makexargs
read the null-terminate (with-0
). – Henrik supports the community Oct 04 '23 at 13:15