1

I am quite new to the terminal stuff and I just couldn't find any answer on the aforementioned subject.

On my OS X, I have a folder with about 4000 pics that I'd like to move into folders that are named according to the modification date (not creation date) of the files. How can I accomplish this using the terminal?

2

With perl:

perl -MPOSIX -le 'for (<*.jpg>) {
  $d=strftime"%Y-%m-%d",localtime((stat$_)[9]);
  mkdir$d;rename$_,"$d/$_" or warn "rename $_: $!\n"}'

With zsh:

zmodload zsh/stat
for f (*.jpg) {stat -F %F -A d +mtime -- $f && mkdir -p $d && mv -- $f $d}
2

With OSX stat:

for file in *; do
    dir="$(stat -t %Y%m%d%H%M%S -f %Sm -- "$file")"
    mkdir -p "$dir"
    mv -- "$file" "$dir/$file"
done

With GNU stat (i.e. on Linux or Cygwin):

for file in *; do
    dir="$(stat -c %Y -- "$file")"
    mkdir -p "$dir"
    mv -- "$file" "$dir/$file"
done

This will move each file into a directory named with its mtime (as an epoch).

If you want finer grained control over how the directory looks, you can use GNU date to reformat it by changing the assignment line to something like this:

dir="$(date -d @"$(stat -c %Y -- "$file")" +%F)"

See man date for information about date format specifications that you can use. In this case, %F is:

%F full date; same as %Y-%m-%d

  • 2
    OS/X has the BSD stat command with a different syntax. – Stéphane Chazelas Jul 16 '13 at 10:31
  • Wow, I am impressed for the quick answer! Thanks! However, I get the message: "stat: illegal option -- c – Dave Jul 16 '13 at 10:38
  • Thanks to @Gilles for the modifications to use OSX stat. – Chris Down Jul 17 '13 at 11:15

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.