0

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.

Pad
  • 103

1 Answers1

2

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).

steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • This gives me the error `rename: invalid option -- 'n'

    Usage: rename [options] expression replacement file...

    Options: -v, --verbose explain what is being done -s, --symlink act on symlink target

    -h, --help display this help and exit -V, --version output version information and exit

    For more details see rename(1). ` and when I run it without -n my filenames don't change :(

    – Pad Jun 16 '21 at 16:49
  • @Pad in that case the implementation of rename that you are using is not one that I am familiar with - my answer applies to the Perl-based one sometimes known as file-rename. – steeldriver Jun 16 '21 at 16:57
  • No problem, when I do -V I get rename from util-linux 2.23.2 thank you for your help! I will keep trying. – Pad Jun 16 '21 at 17:00
  • 1
    @Pad I have added a couple of other options that may suit you better – steeldriver Jun 16 '21 at 17:11
  • 1
  • @steeldriver thank you - this worked perfectly rename -v "_$(date +%Y%m%d)" '' *_*_*.jpg – Pad Jun 17 '21 at 11:11