Problem with special characters on the way (exclamation mark !, Carrot ^, etc.) Using Delayed Expansion

I looked and could not find anything to make my script work with special characters (such as !or ;or ^) in the file path or file name.

My script works, but only if the above characters are not in any of the scanned folders or file names. If any folders or files have these characters, then the script breaks. I need help figuring out how to make my script work with special characters (like above) in the path or file name. Here is my script:

set srcdir=%~dp0%src

set desdir=%~dp0%des

setlocal EnableDelayedExpansion
for /r "%srcdir%" %%f in ("*.txt") do (
    set "subdir=%%~f"
    set "subdir=!subdir:%srcdir%=%desdir%!"
    echo !subdir!
    pause
)
endlocal

Thanks for any help!

+4
2

, , . , , . , . , , call .

@echo off
setlocal

set "srcdir=%~dp0%src"
set "desdir=%~dp0%des"

for /r "%srcdir%" %%f in ("*.txt") do (
    set "subdir=%%~f"

    rem // use call to avoid delayed expansion and preserve exclamation marks
    call set "subdir=%%subdir:%srcdir%=%desdir%%%"

    rem // use set /p rather than echo to exploit quotation marks and preserve carets
    call set /P "=%%subdir%%"<NUL & echo;
    pause
)

, , , , for :

@echo off
setlocal

set "srcdir=%~dp0%src"
set "desdir=%~dp0%des"

for /r "%srcdir%" %%f in ("*.txt") do (
    set "subdir=%%~f"
    setlocal enabledelayedexpansion
    for %%I in ("!subdir:%srcdir%=%desdir%!") do endlocal & set "subdir=%%~I" & echo(%%~I
    pause
)
+3
  • "".
  • set "VAR=Value".
  • : %%~F ; .

:

setlocal DisableDelayedExpansion

set "srcdir=%~dp0src"
set "desdir=%~dp0des"

for /R "%srcdir%" %%F in ("*.txt") do (
    set "subdir=%%~F"
    setlocal EnableDelayedExpansion
    set "subdir=!subdir:%srcdir%=%desdir%!"
    echo(!subdir!
    pause
    endlocal
)
endlocal

, , , . , ...


, , .

, - :

echo(!VAR:%SEARCH%=%REPLACE%!

%SEARCH% %REPLACE% ( ).

%SEARCH% a =, : , %SEARCH% a=b %REPLACE% cd, !VAR:a=b=cd!, a b=cd.

* %SEARCH% : %SEARCH% %REPLACE%. ( , .)

~ %SEARCH% , .. , ; , !VAR:~a=b! , , ~a b .

, %SEARCH% / !, ! , !VAR:a!=b! !VAR:a!, .

+3

All Articles