Search code examples
linuxfilerenametrim

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!


Solution

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