I am trying to rename a series of pdfs from filenames like this: The New Town Cryer - 01 Oct 2020.pdf
to this 2020-10-01_-_The_New_Town_Cryer.pdf
. I've written a bash script that uses sed
to accomplish this, but I'm having trouble figuring out how to convert the date from the current three letter month format using the date
command. This is the line of my script so far (the previous newname
variable is The New Town Cryer - 01 Oct 2020 pdf
:
newname="$(echo "$newname" | sed -re 's/^(.*) - (.*) ([^ ]+)$/echo "$(date -d "\2" "+%Y-%m-%d")-\1".\3/')"
The output from this line is echo "$(date -d"01 Oct 2020" "+%Y-%m-%d")-The New Town Cryer".pdf
, where I was hoping it would be 2020-10-01-The New Town Cryer.pdf
Can anyone tell me where I'm going wrong? Thanks!
Edit: to clarify here is my whole script so far, since it seems that my snippet was unclear. The original format of the filenames is The New Town Cryer - No. 1,032 [01 Oct 2020].pdf
, which I am trying to convert to the format 2020-10-01_The_New_Town_Cryer.pdf
.
#!/bin/bash
find "$1" "*.pdf" -type f -printf "%f\n" | while IFS= read -r f ; do #find all pdfs
name=$f
newname="$(echo "$name" | sed -re 's/\./ /g')" # replace .s with spaces to allow 'date'-command to parse the date
newname="$(echo "$newname" | sed -re 's/\[/!/g')" # replace [s with spaces to allow 'date'-command to parse the date
newname="$(echo "$newname" | sed -re 's/\]/!/g')" # replace [s with spaces to allow 'date'-command to parse the date
newname="$(echo "$newname" | sed -re 's/(.*) - (.*) (!.*!)/\1\ - \3/')" # remove issue number
newname="$(echo "$newname" | sed -re 's/\!//g')" # replace !s with spaces to allow 'date'-command to parse the date
newname="$(echo "$newname" | sed -re 's/^(.*) - (.*) ([^ ]+)$/echo "$(date -d "\2" "+%Y-%m-%d")-\1".\3/')" # reorder the date and name, split at '-', keep the file extension, prepare for date conversion
newname="$(echo "$newname" | bash )"
newname="$(echo "$newname" | sed -re 's/ /./g')" # replace remaining spaces with .
mv "$name" "$newname"
done