So recently, I have tried to make myself a batch script to rename files by replacing a certain string by another. It is sucessful, until you add spaces. This is what my code currently looks like :
@echo off
:0
cls
set /p "str=String to replace : "
set /p "rsw=Replace string with : "
set /p "infile=In file : "
for %%a in ("%infile%") do (
cd %%~dpa
set "fn1=%%~nxa"
call set fn2=%%fn1:%str%=%rsw%%%
ren "%%~dpa%fn1%" "%%~dpa%fn2%"
)
echo "%str%" "%rsw%"
echo "%fn1%" "%fn2%"
pause
goto 0
Solved :
I have modified my code to look like this and now it works :
@echo off
set /p "str=String to replace : "
set /p "rsw=Replace string with : "
title Replace "%str%" with "%rsw%"
:0
cls
set /p "infile=In file : "
for %%a in ("%infile%") do (
set "wkdir=%%~dpa"
set "fn1=%%~nxa"
)
call set "fn2=%%fn1:%str%=%rsw%%%"
cd %wkdir%
ren "%fn1%" "%fn2%"
pause
goto 0
I even tried using setlocal EnableDelayedExpansion
but it didn't help so I simply took the renaming process out of the for
command.
The only problem that I now run into is renaming a file containing spaces in it's name.