Bulk Date Format Renamer

By | Linux, Perl One-Liners

This code shown below will rename any file that contains a date or date range and place the date in the front of the file. So for example:

Filename-Is-This-2020-2021.doc renames to 2020-2021-Filename-Is-This.doc.

This one-liner will also handle dates presented like this:

  • 2020-2021 ~ Full date range.
  • 2020-21 ~ Date range abbreviation.
  • 2020 ~ Only one date.

ONE-LINER

perl -MFile::Copy -lE 'while (glob q[*]) { next if -d; $o = $_; if (s`(?:-+)?(\d{4}(?:-\d{2,4})?)(?:-+)?`-`) { $_ = qq[$1-$_]; s`-+`-`g; say $o, " >> " , &{ sub {s`(?:^|(?<=-))[a-z]`uc $&`ge; $_ }}; rename $o, $_ } }'

.bashrc

You can put the following below in your .bashrc and invoke the script on the command line with dtrn.

function dtrn()
{
        perl -MFile::Copy -lE 'while (glob q[*]) { next if -d; $o = $_; if (s`(?:-+)?(\d{4}(?:-\d{2,4})?)(?:-+)?`-`) { $_ = qq[$1-$_]; s`-+`-`g; say $o, " >> " , &{ sub {s`(?:^|(?<=-))[a-z]`uc $&`ge; $_ }}; rename $o, $_ } }'
}

Leave a Reply

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