1

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
3
  • 2
    "I have a bunch of directories with different revisions of the same c++ project within". Have you considered using source control system? I recommend Git.
    – johnsyweb
    Commented Jan 30, 2012 at 10:02
  • Yes, We are using SVN for the newer projects. Thanks anyway! Is it worth to switch to Git? Does Git have any of significant advantages over SVN?
    – ezpresso
    Commented Jan 30, 2012 at 10:17
  • I prefer Git. Unfortunately the Git vs SVN debate is off-topic for StackOverflow: stackoverflow.com/q/871/78845
    – johnsyweb
    Commented Jan 30, 2012 at 10:37

2 Answers 2

1

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

2
  • Are there any chances to force these scripts to do recursive search?
    – ezpresso
    Commented Jan 30, 2012 at 10:31
  • find does a recursive search. You could, in fact, accept the answer of @choroba, mine is 'slightly' convoluted I guess ;)
    – Hannes
    Commented Mar 21, 2014 at 11:57
1

Another option, mixing your solution with the previous answer:

find -print0 | xargs --null ls -dtl

It shows directories as well.

1
  • Useless use of xargs. There is an -exec option in find. Commented Jan 30, 2012 at 14:27

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