I have made a batch script that replaces strings in a specified text-based file. Within my file, the string OutDir=bin
should be replaced as OutDir=Build
but gets output as bin=OutDir=Build=bin
. How do I escape the =
in OutDir=bin
so that the string doesn't become garbled? I have tried OutDir^=
but using the carrot doesn't work either.
Here is my current script:
@echo off
setlocal enableextensions disabledelayedexpansion
set search=OutDir=bin
set replace=OutDir=Build
set textFile=%DOCUMENT%.txt
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
I have attempted to change the find and replace variables to compensate for the =
in the string I'm replacing but none have worked:
set search= "OutDir=bin"
set replace= "OutDir=Build"
set search="OutDir=bin"
set replace="OutDir=Build"
set "search=OutDir=bin"
set "replace=OutDir=Build"
"set search=OutDir=bin"
"set replace=OutDir=Build"
Answer
Replacing the Equal Symbol =
in a String with Batch using PowerShell
After testing and then research afterwards, I came upon this answer on StackOverflow which then also pointed to this thread and posts on DosTips and replacing the =
with pure batch isn't easy.
When I run into issues with batch scripting where it takes a ton of complex batch logic or just cannot figure out how to get it to work easily, I usually try incorporating some PowerShell into the mix since it's Windows native and it can be much more robust than batch without complex logic.
The below batch script will essentially:
- Use Get-Content and Replace for the string to search and replace
- Then it will use Set-Content to put the newly replaced string back into the file accordingly
Script
@echo off
setlocal enableextensions disabledelayedexpansion
set search=OutDir=bin
set replace=OutDir=Build
set textFile=%DOCUMENT%.txt
:PowerShell
SET PSScript=%temp%\~tmpStrRplc.ps1
ECHO (Get-Content "%~dp0%textFile%").replace("%search%", "%replace%") ^| Set-Content "%~dp0%textFile%">"%PSScript%"
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%'"
EXIT
Output Result
OutDir=Build
No comments:
Post a Comment