Replace string in filename, handling of exclamation marks!
Posted: 23 Nov 2016 20:12
Was writing a simple script for replacing a string for another in filenames (in the provided folder), but I noticed it failed if the strings include "!". I try not to use any special characters in my filenames, but the exclamation marks are not all that rare.
The important bits: (I can paste the whole code if needed)
This works, at least if the strings don't include both "!" and "%". But surely there's a more elegant way to do this, maybe escaping the "!" inside the variable, but I can't figure it out.
Thanks.
The important bits: (I can paste the whole code if needed)
Code: Select all
::usage: strep <folder> <old_string> <new_string>
SETLOCAL DISABLEDELAYEDEXPANSION
::test if ! present
set "_test="
for /f "delims=!" %%A in ("%_search%%_replace%") do set "_test=%%A"
IF "%_test%" NEQ "%_search%%_replace%" set "_excFlag=1"
FOR /F "tokens=*" %%A IN (' dir /b %_dirOpt% "*%_search%*" ') do (
set "_file=%%A"
SETLOCAL ENABLEDELAYEDEXPANSION
IF "%_excFlag%" == "1" (call :renamer _file _search _replace) ELSE REN "!_file!" "!_file:%_search%=%_replace%!"
ENDLOCAL
)
:renamer
set "_fileR=!%~1!"
set "_searchR=!%~2!"
set "_replaceR=!%~3!"
SETLOCAL DISABLEDELAYEDEXPANSION
call set "_new=%%_fileR:%_searchR%=%_replaceR%%%"
REN "%_fileR%" "%_new%"
ENDLOCAL
exit /b
This works, at least if the strings don't include both "!" and "%". But surely there's a more elegant way to do this, maybe escaping the "!" inside the variable, but I can't figure it out.
Thanks.