ezpresso
ezpresso

Reputation: 8126

Get the date of the most recent entry (file or directory) within a directory

I have a bunch of directories with different revisions of the same c++ project within. I'd like to make things sorted out moving each of these directories to a parent directory named by pattern of YYYY.MM.DD. Where YYYY.MM.DD is the date of the most recent entry (file or directory) in a directory.

How can I recursively find the date of the most recent entry in a particular directory?

Update

Below is one of the ways to do it:

find . -not -type d -printf "%T+ %p\n" | sort -n | tail -1

Or even:

find . -not -type d -printf "%TY.%Tm.%Td\n" | sort -n | tail -1

Upvotes: 1

Views: 1694

Answers (2)

choroba
choroba

Reputation: 241898

Another option, mixing your solution with the previous answer:

find -print0 | xargs --null ls -dtl

It shows directories as well.

Upvotes: 1

Hannes
Hannes

Reputation: 484

Try using ls -t|head -n 1 to list files sorted by modification date and show only the first. The date will be in the format defined by your locale (ie YYYY-MM-DD).

For example,

ls -tl | awk '{date=$6; file=$8; system("mkdir " date); system("mv $8 " " date"/")'

will go through all files and create a directory for every modification data and move the file there (beware: care must be taken for filenames containing whitespace). Now use find -type d in the root directory of the source tree to recursively list all the directories. Combined with the above you have now (sadly there is some overhead now):

for dir in $(find -type d) ; do export dir ls -tl dir| awk '{dir=ENVIRON["dir"]; date=$6; file=$8; system("mkdir " dir "/" date); system("mv " dir "/" $8 " " dir "/" date"/")' done

This does not go recursively through the tree, but takes all directories of the complete tree and then iterates over them. If you need the date-directories outside of the source tree (suppose so), just edit the two system() calls in the awk script accordingly.

Edited: fix script, add more description

Upvotes: 1

Related Questions