1

[Edited question to try and make clearer]

Simple one, i think....

I am trying to use the following batch code to replace a string in a text file;

@echo off
set "replace=#user=guest"
set "replaced=user=StoreUser1"

set "source=C:\Users\adam\Desktop\test.txt"
set "target=C:\Users\adam\Desktop\test1.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal

Its not executing as expected, it simply leaves the text unchanged. If however I modify the SET commands (and of course the text in the text file) as;

set "replace=#userguest"
set "replaced=userStoreUser1"

Then this works as expected. I'm assuming the second '=' which is required is causing the SET not to function correctly and needs escaped somehow.

Hope that makes sense and thanks in advance!

Adam

dbenham
  • 127,446
  • 28
  • 251
  • 390
Adam_231
  • 61
  • 1
  • 1
  • 8

1 Answers1

2

It is impossible to escape the = within the find string. So it is impossible to do a variable expansion find/replace if the find string contains =.

This was investigated thoroughly at https://www.dostips.com/forum/viewtopic.php?f=3&t=1485. Various strategies were explored to get around the problem. But I don't think you want to go down that rabbit hole.

This is one of many reasons why editing text files via batch is generally not a good idea.

You could try PowerShell, I'm sure that would be fairly easy, if you know that scripting language.

Or you could use my JREPL.BAT regular expression find/replace utility. It is pure script (hybrid JScrpt/batch) that runs natively on any Windows machine from XP onward - no 3rd party exe required. Full documentation is embedded within the script, and available from the command line via jrepl /?, or jrepl /?? for paged help. /jrepl /?help lists all the various forms of help. For example, jrepl /?options gives a brief summary of each option.

call jrepl "#user=guest" "user=StoreUser1" /f "C:\Users\adam\Desktop\test.txt" /o "C:\Users\adam\Desktop\test1.txt"

or

set "replace=#user=guest"
set "replaced=user=StoreUser1"

set "source=C:\Users\adam\Desktop\test.txt"
set "target=C:\Users\adam\Desktop\test1.txt"

call jrepl replace replaced /v /f "%source%" /o "%target%"

If you want to overwrite the original file, then

set "replace=#user=guest"
set "replaced=user=StoreUser1"

set "source=C:\Users\adam\Desktop\test.txt"

call jrepl replace replaced /v /f "%source%" /o -
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • @Adam_231 - dbenham does good stuff. It is a lot of work to produce something that can do what `sed` does so easily. – lit Oct 05 '18 at 15:27