Renaming files from YYMM(DD) to ISO YYYY-MM(-DD)

I wrote a script and decided to try out code display here by posting it. I know tools like rename do this but I like to see what will be done before I go doing it so I am quite fond of generating scripts I can pipe to /bin/sh

Enjoy ūüôā

datename-to-iso.sh

#!/bin/sh
find . -depth -regextype egrep -regex '^\..*/[0-9]{4,6}.*' | while read -r file; do
  # YYMMDD becomes YYYY-MM-DD
  newfile=$(echo "$file" | sed -nre '/[0-9]{4,6}(\.|-[0-9]{2}).*/!p' \
    | sed -re \
    's/(^.*)\/([0-9]{2})([0-9]{2})([0-9]{2})([^0-9\/]+$)/\1\/20\2-\3-\4\5/'
  )

  # If not, then YYMM becomes YYYY-MM
  if [ "$newfile" = "$file" ]; then
    newfile=$(echo "$file" | sed -nre '/[0-9]{4,6}(\.|-[0-9]{2}).*/!p' \
      | sed -re \
      's/(^.*)\/([0-9]{2})([0-9]{2})([^0-9\/]+$)/\1\/20\2-\3\4/'
    )
  fi

  # Did we come up with a new filename?
  if [ -n "$newfile" ] && [ "$newfile" != "$file" ]; then
    echo mv -v "\"$file\"" "\"$newfile\""
  fi
done

(updated 2016-09-15)

Leave a Reply

Your email address will not be published. Required fields are marked *