3

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?

4

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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.