Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: How to batch rename files, trimming characters in the middle, and end of the filename

I have around a thousand files I need to rename. The filenames all look like this

XXXXppppppp-ppppp_S!!_L001XXX_001.extension

Where X is information I need to keep and ! is a sequentially increasing number (ie. 01, 02...99).

I really can't get my head around the rename command, and how to go about achieving what I need to do. Essentially I want to keep the first four characters, delete the next 22, keep the next 3 and delete the final 4. I would like to also retain the extension.

Thanks!

like image 251
DanielHolden Avatar asked Sep 16 '25 13:09

DanielHolden


1 Answers

Try doing this :

rename -n 's/^(.{4}).{22}(.{3}).{4}(\..*)/$1$2$3/' *

Verify that your rename command is the perl's one, sometimes there's another one installed. The good one is sometimes called prename.

When tests are OK, remove the -n switch (dry-run).

like image 77
Gilles Quenot Avatar answered Sep 19 '25 04:09

Gilles Quenot