Search code examples
regexperlreplacebatch-rename

Regexp replace (some) numbers with letters in names


I have a list of files:

file1_1.pdf file1_2.pdf file1_3.pdf

However, I want them to be renamed as

file1_a.pdf file1_b.pdf file1_c.pdf

I wonder how can I substitute letters for numbers in filenames (I use the rename perl script, which relies on standard regexp); unfortunately, tr is of no help, as it would substitute numbers where I don't want it to.


Solution

  • You could try something like this:

    rename 's/_\K(\d+)(?=.pdf$)/chr ((ord "a") + $1 - 1)/e' *.pdf
    
    • The e option to the substitution operator is used to convert the digit to a lowercase character, see perlop for more details on the s///e operator.
    • To avoid removing the underscore in front of the digit, we use the zero-width lookbehind assertion \K, see perlre for more details.
    • To avoid removing the .pdf extention following the digit, we use a (?=pat) zero-width positive lookahead assertion, also see perlre.