Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively find and list the latest modified files in a directory with subdirectories and times

  • Operating system: Linux

  • Filesystem type: ext3

  • Preferred solution: Bash (script/one-liner), Ruby, or Python

I have several directories with several subdirectories and files in them. I need to make a list of all these directories that is constructed in a way such that every first-level directory is listed next to the date and time of the latest created/modified file within it.

To clarify, if I touch a file or modify its contents a few subdirectory levels down, that timestamp should be displayed next to the first-level directory name. Say I have a directory structured like this:

./alfa/beta/gamma/example.txt 

and I modify the contents of the file example.txt, I need that time displayed next to the first-level directory alfa in human readable form, not epoch. I've tried some things using find, xargs, sort and the like, but I can't get around the problem that the filesystem timestamp of 'alfa' doesn't change when I create/modify files a few levels down.

like image 330
fredrik Avatar asked Apr 06 '11 12:04

fredrik


People also ask

How do I find the latest modified file in Linux?

Finding Files Modified on a Specific Date in Linux: You can use the ls command to list files including their modification date by adding the -lt flag as shown in the example below. The flag -l is used to format the output as a log. The flag -t is used to list last modified files, newer first.

How can I tell when a file was last modified?

File Explorer has a convenient way to search recently modified files built right into the “Search” tab on the Ribbon. Switch to the “Search” tab, click the “Date Modified” button, and then select a range. If you don't see the “Search” tab, click once in the search box and it should appear.

How can I list subdirectories recursively?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.


2 Answers

Try this one:

#!/bin/bash find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head 

Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).

If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs instead:

#!/bin/bash find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head 

which is a bit faster.

like image 125
Heppo Avatar answered Sep 24 '22 11:09

Heppo


To find all files whose file status was last changed N minutes ago:

find -cmin -N 

For example:

find -cmin -5 
like image 42
iman Avatar answered Sep 22 '22 11:09

iman