1

I have written a simple script which will find and replace a matching string. I am getting issue in the output file. Following is my script

@echo off
setlocal ENABLEDELAYEDEXPANSION

for /f "tokens=1 delims=" %%a in ('FINDSTR "^applicationPort" "E:\BATCH-SCRIPTING\Version.txt"') do (
    echo Installed version is %%a
    set oldPort=%%a
)

for /f "tokens=1 delims=" %%b in ('FINDSTR "^applicationPort" "E:\BATCH-SCRIPTING\Sample.txt"') do (
    echo Installed version is %%b
    set newPort=%%b
)

set SEARCHTEXT="applicationPort=8080"
set REPLACETEXT="applicationPort=8090"

set file="E:\BATCH-SCRIPTING\Sample.txt"

for /f "tokens=1,* delims=]" %%A in ('"type %file% |find /n /v """') do (
set "line=%%B"
if defined line (
call echo %%line:%SEARCHTEXT%=%REPLACETEXT%%%>> %file%_new
) ELSE echo.
)

move /Y %file%_new %file% > nul

In my output file the expected output should be : applicationPort=8090, but i am getting 8080=applicationPort=8090=8080.

Can anyone help me in resolving this issue.

unclemeat
  • 5,029
  • 5
  • 28
  • 52
Gikar
  • 219
  • 1
  • 6
  • 17

1 Answers1

1

Look at what your key replacement line would like like after the first round of variable expansion:

call echo %%line:%SEARCHTEXT%=%REPLACETEXT%%%>> %file%_new

becomes

call echo %line:applicationPort=8080=applicationPort=8090%>>"E:\BATCH-SCRIPTING\Sample.txt"

The search/replace parser ends the search phrase at the first = it sees. So after the CALL it searches for applicationPort and replaces it with 8080=applicationPort=8090. Perfectly logical.

The bad news is there is absolutely no way to escape the = in the search term. Replacing = is extremely difficult using a batch file. There are solutions, but I don't recommend them. Instead, I would use my hybrid JScript/batch utility called REPL.BAT. It is pure script that will run on any Windows machine from XP onward. It performs a regex search and replace on stdin and writes the result to stdout. Full documentation is embedded within the script.

@echo off
type "E:\BATCH-SCRIPTING\Sample.txt"|repl "applicationPort=8080" "applicationPort=8090" >"E:\BATCH-SCRIPTING\Sample.txt_new"
move /y "E:\BATCH-SCRIPTING\Sample.txt_new" "E:\BATCH-SCRIPTING\Sample.txt" 

REPL.BAT is much simpler and faster (and more powerful) than anything you can do using pure batch script.

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390