Timelapse: BASH renaming files based on creation date

12 May

I have been creating a lot of time-lapse images recently as part of my research, which I’ve been stacking into GIFs with ImageJ. However, sometimes I set up my timelapse program to name the image files something useless, like an incrementing value, which made sorting the images a pain! I really needed them renamed to the date/time of creation. I was also planning on using the filename in my ImageJ plugin as the time-stamp for labelling the time-lapse GIFS (post about this soon).

To fix this, here is a little bash script that will; parse all the files in a specified directory, with a specified extension (such as jpeg, png, sif), and create a copy in a new folder with the datestamp as the filename. You might find it useful!

[sourcecode language=”bash” wraplines=”false” collapse=”false”]

#!/bin/bash
# rename_timelapse_images.sh – Small bash script to copy all files of specific format in a new folder and rename based on the "date modified" file attributes.
#
# Usage: ./rename_timelapse_images.sh FileContainingImages NewFileName FileExtension
# e.g. ./rename_timelapse_images.sh timelapsefolder newfolder sif
#
# Created by Gordon Wellman, gordon.wellman@alumni.adelaide.edu.au

mkdir $2; # Creates a directory

for f in $1/*.$3; # For all files with specified extension
do
#obtain file attributes and craft into a useable string
i=$(stat -c %y "$f" | cut -d’.’ -f1);
#remove the ‘:’ which isn’t allowed for files in windows
i=$(echo "$i" | tr ‘:’ ‘-‘);
#report process
echo "Processing /$f -> $2/$i.$3";
#copy file and rename with new file name with extension
cp "$f" "$2/$i.$3";
done

[/sourcecode]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.