Search code examples
batch-filebatch-processing

Batch file to rename files in a folder and back again


A slightly archaic question I'm afraid but here goes:

I have a program which produces some .RAW files in a sequence eg.

Example_1.RAW
Example_2.RAW

This then adds extra significant figures to the number as necessary, eg.

Example_10.RAW
Example_200.RAW

I have a need to convert these file names into numbers for running through a batch processor that then produces more files as outputs. I've written a batch file that does the renaming and stores the old and new filenames in a text file, my code is:

@echo off
set i=1
echo Running Batch Rename
for %%f in (*.RAW) do (set file=%%f) & CALL :rename

:rename
echo %i% >>Names.txt
echo %file% >>Names.txt
echo. >>Names.txt
ren %file% %i%.RAW
set /A i+=1

This then renames all my .RAWs as 1.RAW, 2.RAW etc and creates Names.txt with the old and new filenames. Thanks to the way in which DOS processes numbers this does mean that I get a slightly wonky numbering process, ie it will process Ex_1, Ex_10, Ex_100, Ex_101 as 1, 2, 3, 4 which would lead to more work in the post processing of these results in order to get the right results in the right places.

Would it be possible to write another batch file that takes the Names.txt and reverses the process for the output files? So it will take a folder with 1.raw, 1.something, 1.something else, refer to the Names.txt and rename them to Example_1.raw etc?


Solution

  • This should do the job

    @echo off
    set cnt=0
    del Names.txt > nul 2>&1
    echo Running Batch Rename
    for %%f in (*.RAW) do (
        set "file=%%f"
        CALL :renameToNumber
    )
    echo .. Do the jobs ...
    rem ** As sample: copy the file
    copy *.raw *.some
    call :renameBack
    exit /b
    
    :renameToNumber
    set /A cnt+=1
    set "number=00000%cnt%"
    set "number=%number:~-4%"
    (echo %number% %file%) >> Names.txt
    ren "%file%" %number%.RAW
    exit /b
    
    :renameBack
    for /F "tokens=1,*" %%A in (names.txt) DO (
       set "number=%%A"
       set "filename=%%~nB"
       call ren %%number%%.* "%%filename%%_%%number%%.*"
       call echo ren %%number%%.* "%%filename%%_%%number%%.*"
    )
    exit /b