Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

Rename Files to Modified Time with Perl

We were processing hundreds of recordings for a client, but they didn’t know the dates on the files because moving between systems changed the date time stamp. The solution was to programatically rename the files with their modified time so no matter where the file went, we would always know it’s date.

This is just a snippet that we wanted to save and thought you might find it useful.

What to Learn From this Perl Script

  • Get an Array of Files

  • Loop over and Array

  • Extra Modified Time from Files using Stat

  • Rebuild File names Based on our Desire

  • Rename Files, Programmatically

Perl Source Code to Rename Files with Dates


# standard modules
use warnings;
use strict;

# allows us to get the time parts
use POSIX 'strftime';

# glob a set of files, modify as it suits you
my @files = <*.wav>;

# loop over the array, extract file information from each
# stat() puts the data into several variables
foreach my $file (@files){
	my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($file);

	# ok now format the time the way we like.
	my $date = strftime '%Y.%m.%d-%H.%M.%S', localtime $mtime;

	# and then massage the actual name to something more sanitized
	my $f = $file;
	$f =~ s/\s+/ /g; # replace all spaces with 1 space
	$f =~ s/ /\-/g;  # replace one space with 1 dash, as many times as you find it

	# we have our name, so lets do the actual renaming
	rename "$file", "$date\-$f";

Custom Perl Programming

Do you have problems that you want solved by automation or scripting? Contact us for custom Perl programming. We can write small and large scripts for system administration, or every day tasks such as renaming files.

Last updated on 13 Jul 2019
Published on 13 Jul 2019