grep -r does a recursive search in all files in a particular directory. However, if I want these files to be read by grep in the order of their last modified time, how do I do that?

2 Answers 2


With zsh:

grep -- foo **/*(D.om)

With GNU tools:

find . -type f -printf '%T@\t%p\0' |
  tr '\n\0' '\0\n' |
  sort -rg |
  cut -f2- |
  tr '\n\0' '\0\n' |
  xargs -r0 grep foo

If you don't have something like zsh, this isn't entirely trivial. It's probably more efficient to get the hits, then sort by the modification time of each file with a hit.

grep -rl 'regex' . |
while read -r file; do
    stat -c '%Y:%n' "$file"
done | sort | cut -d: -f2-

This will obviously break if you have file names with newlines on their names or something.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .