Search code examples
batch-filebatch-rename

Apply a prefix of arbitrary length to a directory of files with batch file


I have an existing batch file while I use to create project files from a set of template files. The batch file creates a folder structure, and copies a series of files into them. Most of these files are named using the same structure, for example:

PPPP-123_456a.dwg

My batch file currently uses the following line to replace “PPPP” with the actual project number:

for /r "%ProjDir%" %%f in (PPPP*) do (rename "%%f" "%ProjectNumber%*")

Where ProjDir is the path to the folder created by the batch file, and ProjectNumber is the project number.

Which works fine. My problem is that some client project numbers are now up to 5 figures, while other project numbers are at 4 figures. I need to modify this line to work correctly for either 4 or 5 digit project numbers.

Things I have tried:

If I use it as-is with project number of 12345, my file name changes from PPPP-123_456a.dwg to 12345123_456a.dwg - rather than inserting the extra character, the rename command just overwrites existing characters so I lose the first dash in the filename.

If I rename all the template files to start with PPPPP, I then can’t use it on a four-digit project number or the result will be 1234P-123_456a.dwg.

If I delete all the leading P’s from the template files and then modify the code to:

for /r "%ProjDir%" %%f in (PPPP*) do (rename "%%f" "%ProjectNumber%%%f")

…then it tries to apply the project number prefix to the beginning of the file path, not the file name (i.e. it tries to rename C:/Test/-123_456a.dwg to 12345C:/Test-123_456a.dwg). This seems like my closest attempt so far, I just need to find a way to make it apply the prefix to the filename part of the string, not the whole string. But I’m not sure how to do that.

TL;DR, How can I use a batch file to correctly apply a prefix of arbitrary length to a directory of files?


Solution

  • Apologies for the radio silence, got called away to a more urgent project.

    I managed to simplify things slightly by removing the PPPP from the start of each file, and then just building the new filename as @aschipfl suggested. This also allows me to use the same technique on the handful of other files that don't follow the same filename structure as above.

    for /r "%ProjDir%" %%f in (*.dwg) do (rename %%f %ProjectNumber%%%~nf%%~xf)
    

    %ProjectNumber% returns a project number with any number of digits

    %%~nf returns the filename of the file being operated on

    %%~xf returns the extension of the file being operated on

    I had initially also tried to use %%~df and %%~pf to retrieve the drive and path components of the new filename, but TIL that when using the rename command, you must specify the full file path on the source file, but only the filename on the destination file