The code fragment below in a batch file works perfectly fine, but doesn't work when there are ampersands in the string variable, which unfortunately will happen in the project I'm working on. Is there a way to rewrite these two statements so that the ampersands don't hijack the execution of the statements?
My apologies if the "purpose" of this isn't apparent; I would have to paste an overwhelming number of lines to make it truly apparent what I'm trying to do. I'm hoping people can focus on the micro level of these lines rather than letting the apparent lack of "big picture" get in the way.
Other than this batch file, there is a file called file.txt that has just one line in it: /Here and There/Over & Yonder/This & That
. Here is the batch file code:
setlocal enabledelayedexpansion
set "FolderName=This & That"
set "ChosenFolder=Here & There/Over & Yonder/This & That"
set "NewFolder=Yin & Yang/Up & Down"
:: Ideally the following problematic line would change the value of %ChosenFolder% to 'Here & There/Over & Yonder', but the ampersands make it fail
For /f "delims=" %%a in ("/!FolderName!") do set "ChosenFolder=!ChosenFolder:%%a=!"
set /a count=0
:: The next problematic line should search file.txt for a string that matches "/Here & There/Over & Yonder" and count the number of matches, but the ampersands make it fail
for /f "delims=" %%a in ('findstr /i /n /c:"/!ChosenFolder!" file.txt" ^| find /c /v ""') do set "count=%%a">nul
:: And finally this problematic line is supposed to actually replace the string with "Yin & Yang/Up & Down"
if %count% gtr 0 type file.txt"|jrepl "/!ChosenFolder!" "/!NewFolder!" /l >temp.txt
echo.
echo FolderName: %FolderName%
echo ChosenFolder: %ChosenFolder% - should be "Here & There/Over & Yonder"
echo NewFolder: %NewFolder% - should be "Yin & Yang/Up & Down"
echo.
echo file.txt should display "Yin & Yang/Up & Down"
type file.txt
echo.
This is not something solvable by simply escaping various characters. The strings themselves must be "Yin & Yang" etc., not Yin && Yang
, Yin ^& Yang
, etc. as they will be used for filenames, titles of pages, etc., and the escaping characters themselves would end up displaying. I've seen really tricky solutions to this type of thing before like putting call
in front of statements, wrapping statements in parentheses, or, as I try to do below, sticking them in for
loops... I just haven't been able to crack it myself.
This uses jrepl.bat, which can be found here. As a side note, I'm happy to consider alternatives for text file search/replace that don't require me to put my eggs in some .exe command line utility that might not be supported in Windows 12 or Windows 13, such as a wonderful "srch.exe" file that I used like 20 years ago but no longer works today.