Search code examples
bashlast-modified

Append a file's last modification date to its name


I'm struggling to find a way to get the last modification date of every file in a folder and subfolders and append them to their names accordingly. So far I can only append a custom text per file, in this case it's _Suffix from this command: find * -exec mv {} {}_Suffix \;

Maybe this isn't the best way since my text is inserted at the very end of the file so it changes the file's extension but at least it works :)

But I want to know how to insert the last modification date instead of _Suffix and do that for every file recursively.


Solution

  • find . -type f -exec bash -c 'for arg; do arg=${arg#./} mod=$(stat -c %x "$arg") base=${arg%.*} ext=${arg#$base}; echo mv -i "$arg" "${base}_${mod%% *}$ext"; done' _ {} +
    

    (multiline version for readability):

    find . -type f -exec bash -c 'for arg; do
      arg=${arg#./} mod=$(stat -c %x "$arg") base=${arg%.*} ext=${arg#$base}
      echo mv -i "$arg" "${base}_${mod%% *}$ext"
    done' _ {} +
    

    I left the echo there for you to see what it's going to run before actually running it. Remove it once you're sure you want to move the files.

    It adds what you want before the extension but it will completely FAIL if:

    • A filename doesn't contain a dot
    • That file is in a folder path which does contain a dot

    It will also not work properly on files with double extensions, e.g. .tar.gz

    Explanation: I'm passing all files to a bash script with find . -type f -exec bash -c '...' _ {} + The bash script does the same action for all files: get the modification date, discover the basename and the .extension, then rename the file to basename_date.extension