Renaming a bunch of files with date modified timestamp at the end of the filename?

here's a version of goldschrafe's one-liner that:

  • doesn't use stat
  • works with earlier versions of GNU date
  • correctly copes with any spaces in the filenames
  • also copes with filenames beginning with a dash

    for f in *; do mv -- "$f" "$f-$(date -r "$f" +%Y%m%d)"; done


Quick-and-dirty Bash one-liner to rename all (globbed) files in the current directory from filename.txt to filename.txt-20120620:

for f in *; do mv -- "$f" "$f-$(stat -c %Y "$f" | date +%Y%m%d)"; done

An enterprising Bash nerd will find some edge case to break it, I'm sure. :)

Obviously, this doesn't do desirable things like checking whether a file already has something that looks like a date at the end.


Obligatory zsh one-liner (not counting the one-time loading of optional components):

zmodload zsh/stat
autoload -U zmv
zmv -n '(*)' '$1-$(stat -F %Y%m%d +mtime -- $1)'

We use the stat builtin from the zsh/stat module, and the zmv function to rename files. And here's an extra which places the date before the extension, if any.

zmv -n '(*)' '$1:r-$(stat -F %Y%m%d +mtime -- $1)${${1:e}:+.$1:e}'

Tags:

Date

Rename

Files