Using Date within Rename command

I have files with names as follows: YYYY-MM-DD_THIS_IS_THE_TITLE.PDF

I want to rename them to the following format: THIS_IS_THE_TITLE_-_MONTH_YEAR.PDF

I am using the YYYY-MM-DD to convert to MONTH_YEAR.

This is being done on a Ubuntu 18.04 machine.

I have already figured out how to do what I want with using a for loop with CUT & MV.

However, for the life of me I can't figure out why the following doesn't work:

rename -n -v "s/^(\d\d\d\d-\d\d-\d\d)_(.+)\.pdf/\$2_-_$(date -d $1 +%B_%Y).pdf/" *.pdf

I can't figure out why the $1 in date isn't being utilized. If I put in an actual date vice the $1 it works just fine.

If I run the following:

rename -n -v 's/^(\d\d\d\d-\d\d-\d\d)_(.+)\.pdf/\$2_-_\$1.pdf/' *.pdf

It will show the file as THIS_IS_THE_TITLE_-_YYYY-MM-DD.PDF, so I know it's using $1.

Can anyone provide some insight on what I'm doing wrong and/or not "escaping" properly? It's a matter of principal now to figure this out.

try escaping $1 - \$1

I should apologize for not listing the million things I've tried and didn't work. But then no one would read any of it.

When I escape the $1 with \$1, I get the error message: invalid date '$1'

I've also tried enclosing the $1 as ${1} which gives error message: invalid date ‘+%B_%Y’

In addition to both error messages above, the output on the command line for each is THIS_IS_THE_TITLE_-_.PDF i.e. skipping the date part completely.

I've also tried single quote and double quotes around $1.

you're using perl-based version of rename - unfortunately not all distros ship that - most ship non-perl based version that (it seems) doesn't support perl-ish regex and/or captures/back-references.
hence I cannot test anything...

try:

rename -n -v "s/^(\d\d\d\d-\d\d-\d\d)_(.+)\.pdf/\$2_-_$(date -d '$1' '+%B_%Y').pdf/" *.pdf
1 Like

You are correct, there are TWO versions of RENAME. Ubuntu does have the other one as well. It's just called rename.ul and is in /usr/bin along with the rename I've been using.

I did try your suggestion with the single quotes and am still getting the same error message:

invalid date ‘$1’

I give up at this point. I've wasted WAY WAY too much time trying to solve this. I'm sure there's a way, it's just beyond my knowledge level.

1 Like

Hello evrybody
try this

rename -n '@D=/^(\d*)-(\d*)-\d*_(.*)\..*/;use POSIX qw(strftime);
$d=strftime "%B_%Y",0,0,0,0,@D[1],@D[0]-1900;s/^[^.]*/@D[2]_$d/' *pdf

For me, this is purely sports interest, it is easier to use a loop in shell

Slightly tweaked

rename -n '@D=/^(\d*)-(\d*)-\d*_([^.]*)/;use POSIX qw(strftime);
$d=strftime "%B_", 0,0,0,0,@D[1],0;s/[^.]*/@D[2]_$d@D[0]/' *pdf

Don't forget about localization LC_ALL=C prename...

2 Likes

Excellent idea to take the Perl door of the Perl wrapper!

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.