I use this command to find all the file in a directory that contains a specific string:

grep -lir "string" path_to directory


grep -lir "users" /var/www/mysite

This command displays all files in the specified directory that contain the string 'users'. However, I want to sort them by descending modification date; newest to the oldest.

Any help?


First we use the Z option then at the other end xargs with -0 option will catch the file names and stat them, sort and remove the timing info to reveal a sorted newest first list.

 grep -Zlir users /var/www/mysite | xargs -0 -r stat --format='%Y+%n' | sort -t+ -k 1,1nr | cut -d+ -f2-

With zsh:

print -rl ./**/*(.De_'grep -qi "string" $REPLY'_om)

This uses glob qualifiers to select only the regular files (.) that contain string (i.e. the glob results for which the expression e_'grep -qi "string" $REPLY'_ returns true) and then via om sorts the final results by mtime (newest first). Remove the D if you don't want to search for hidden files.

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.