Remove today's date string from all filenames in folder
I have a folder full of jpegs formatted like this:
0001_20210516_XYZ.jpg
0002_20210516_XYZ.jpg
123_20210516_XYZ.jpg
01_20210516_XYZ.jpg
and I want to rename all files so the date string in the middle is removed so the files look like:
0001_XYZ.jpg
0002_XYZ.jpg
123_XYZ.jpg
01_XYZ.jpg
I tried using this answer to write the regex to remove 8 digits using this code:
rename - 's/^_\d{8}\_//' *
But this did not do anything. I am not sure how to format this correctly so the middle date string is removed.
To remove the first underscore and following 8 digits using the Perl-based rename
(aka file-rename
), you need to drop the start-of-line anchor ^
, and the second underscore (else you'll end up with 0001XYZ.jpg
etc.)
So:
rename -n 's/_\d{8}//' *_*_*.jpg
Alternatively you could use mmv
(from the Ubuntu package of the same name):
mmv -n '*_*_*.jpg' '#1_#3.jpg'
In either case, the -n
is for testing - remove it when you are happy with the proposed changes.
If you're stuck with the version of rename from util-linux
(which is installed as rename.ul
on my system) then likely the best you will be able to do is match the literal string _20210516
:
rename.ul -vn _20210516 '' *_*_*.jpg
If you really need to remove today's date you could generalize that to
rename.ul -vn "_$(date +%Y%m%d)" '' *_*_*.jpg
(Note that rename.ul from util-linux 2.34
does support a -n
option, which I'm using here for demonstration purposes - adjust accordingly if your version doesn't).