Question

I've seen people do this in Perl, but I'm wondering if there's a way to do it via batch? It's built into Windows, so I think it would be more useful to know how to do this with a batch script. It doesn't require installing anything onto a computer.

An example input name: myFile_55 An example output pattern: change myFile to picture and reduce the number by 13. An example output: picture_42.

How would you approach this? I know a batch command to rename:

ren myFile_55 picture_42.

So, if I have a file named renamer.bat, I can add the following:

for /r %%x in (%1) do ren "%%x" %2.

Then I can type this command:

renamer.bat myfile* picture*.

I don't know how to reduce the numbers, though.

No correct solution

OTHER TIPS

You can probably put the original file name through a for loop, and extract the name and numbers, do the math on the numbers, then plug it back in with the new name and number. As long as the filename format is name_number you can use this:

REM Allow for numbers to be iterated within the for-loop i.e. the i - z
SETLOCAL ENABLEDELAYEDEXPANSION
SET i=0
SET z=13
SET newName=picture
SET workDir=C:\Path\To\Files

REM Given that filenames are in the format of 'Name_number', we're going to extract 'number
REM and set it to the i variables, then subtract it by 13, then rename the original file
REM to what the newName_x which if the filename was oldName_23 it would now be newName_10
FOR /r %%X in (%1) do (
  FOR /F "tokens=1-2 delims=_" %%A IN ("%%X") DO (
    SET i=%%B
    SET /A x=!i! - %z%

    REM ~dpX refers to the drive and path of the file
    REN "%%~dpX\%%A_%%B" "%newName%_!x!"
  )
)

EDIT: Edited the REN command to include the drive and path of the original file. Changed from lower case x to upper case X as to not confuse %%~dpX.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top