Ok, I had a few moments to have a think about this and tried to do it using the rusty old tools that Apple ships (bash
v3.3, sed
the ancient, and antiquated find
) rather than introducing new dependencies.
Let's do this incrementally:
- find the files
- iterate over them
- work out the changes
- check the changes and make them
First thing is to identify your files. I think the following should find all PDFs that start with 4 digits followed by an underscore:
find /Users/YOURUSER -iregex ".*/[0-9][0-9][0-9][0-9]_.*\.pdf" 2> /dev/null
If that's correct, let's pipe it into a while
loop and check that looks correct:
find /Users/YOURUSER -iregex ".*/[0-9][0-9][0-9][0-9]_.*\.pdf" -print0 2> /dev/null |
while IFS= read -r -d $'\0' path; do
print "$path"
done
Now see if we can twiddle your year off the front and onto the back:
#!/bin/bash
find /Users/YOURUSER -iregex ".*/[0-9][0-9][0-9][0-9]_.*\.pdf" -print0 2> /dev/null |
while IFS= read -r -d $'\0' path; do
d=$(dirname "$path")
f=$(basename "$path")
# Strip trailing PDF extension case insensitively and swap 4-digit year followed by underscore, space or dash, from front to back
f=$(echo "$f" | sed -E 's/\.pdf$//i; s/^([0-9]{4})[_ -](.*)/\2\1/')
new="${d}/${f}.pdf"
echo "$path becomes"
echo "-> $new"
# mv "$path" "$new"
done
If that all looks good with your files on your system, make a TimeMachine backup first, then uncomment the penultimate line by removing the #
at the start and run again.
In case you are unfamiliar with sed
, \1
refers to whatever was captured in the first set of (...)
on the left side of the substitution and \2
refers to whatever was captured in the second set of (...)
- they are "capture groups".