Search code examples
bashfilefor-loopfile-renamebatch-rename

How to match numbering of files across different folders e.g. rename NAME9.txt to NAME00009.txt


I have a huge list of files, they came through different processes, so for some reason the ones in the first folder are numbered like this

A9.txt A1.txt while the ones in the other have A00009.txt A.00001.txt I have no more than 99837 files so only four "extra" 0 on one side.

I need to rename all the files inside one folder so the names matches. Is there any way to do this in a loop? Thanks for the help.


Solution

  • You should take a look at perl-rename (Sometimes called rename) Not to be confused with rename from util-linux.

    perl-rename 's/\d+/sprintf("%05d", $&)/e' *.txt
    

    The above script will rename all .txt files in a directory to the following:

    A1.txt       -> A00001.txt
    A10.txt      -> A00010.txt
    Hello225.txt -> Hello00225.txt
    

    Test it Online