filedateapplescriptdatemodified

change folder modified date based on most recent file modified date in folder


I have a number of project folders that all got their date modified set to the current date & time somehow, despite not having touched anything in the folders. I'm looking for a way to use either a batch applet or some other utility that will allow me to drop a folder/folders on it and have their date modified set to the date modified of the most recently modified file in the folder. Can anyone please tell me how I can do this?

In case it matters, I'm on OS X Mavericks 10.9.5. Thanks!


Solution

  • If you start a Terminal, and use stat you can get the modification times of all the files and their corresponding names, separated by a colon as follows:

    stat -f "%m:%N" *
    

    Sample Output

    1476985161:1.png
    1476985168:2.png
    1476985178:3.png
    1476985188:4.png
    ...
    1476728459:Alpha.png
    1476728459:AlphaEdges.png
    

    You can now sort that and take the first line, and remove the timestamp so you have the name of the newest file:

    stat -f "%m:%N" *png | sort -rn | head -1 | cut -f2 -d:
    

    Sample Output

    result.png
    

    Now, you can put that in a variable, and use touch to set the modification times of all the other files to match its modification time:

    newest=$(stat -f "%m:%N" *png | sort -rn | head -1 | cut -f2 -d:)
    touch -r "$newest" *
    

    So, if you wanted to be able to do that for any given directory name, you could make a little script in your HOME directory called setMod like this:

    #!/bin/bash
    # Check that exactly one parameter has been specified - the directory
    if [ $# -eq 1 ]; then
       # Go to that directory or give up and die
       cd "$1" || exit 1
       # Get name of newest file
       newest=$(stat -f "%m:%N" * | sort -rn | head -1 | cut -f2 -d:)
       # Set modification times of all other files to match
       touch -r "$newest" *
    fi
    

    Then make that executable, just necessary one time, with:

    chmod +x $HOME/setMod
    

    Now, you can set the modification times of all files in /tmp/freddyFrog like this:

    $HOME/setMod /tmp/freddyFrog
    

    Or, if you prefer, you can call that from Applescript with a:

    do shell script "$HOME/setMod " & nameOfDirectory
    

    The nameOfDirectory will need to look Unix-y (like /Users/mark/tmp) rather than Apple-y (like Macintosh HD:Users:mark:tmp).