How can i search for "//packages/thirdparty/release/main.txt #10" and replace #10 with #15(set VARIABLE="#15") using batch commands and also ignoring spaces. #10 can be anything, lets assume #XXX. example in command line is preferred.


   //packages/thirdparty/release/config.txt                    #8
   //packages/thirdparty/release/config2.txt   #3
   //packages/thirdparty/release/config1.txt    #4
   //packages/thirdparty/release/main.txt            #10

This is my try

set $FindStr=//packages/thirdparty/release/main.txt#10
set $ReplString=//packages/thirdparty/release/main.txt#15

setlocal enabledelayedexpansion
for /f "delims=" %%a in ('type testlog.txt') do (
   set $Ver=%%a
   set $Ver=!$Ver: =!
   If /i !$Ver!==%$FindStr% set $Ver=%$ReplString%
   echo !$Ver! ) >> testlog.txt
  • In Windows, a command can be executed for multiple files using the forfiles command. The /s option tells it to search directories recursively. forfiles /s /m *.txt /c "perl -pi -e s/search-term/replace-term/g @path" Substitute @path with /p \path\to\start\search\ to start the search from a different path than the current directory. Source: stackoverflow.com/questions/5482900/… – karel Mar 10 '15 at 20:05

You could use the REPL.BAT script to do this. Just save it and run it like this:

 type testlog.txt|repl.bat "#\d\d?$" "#15"

If you only wanted to replace a certain number then you just need a slight modification:

 type testlog.txt|repl.bat "#10$" "#15"

If you want even more control over how things are replaced then you could use another script for that:

COPY /A testlog.txt textlog.out.txt >nul
FOR %%S IN ( 1 3 4 8 10 20 ) DO (
    COPY /A textlog.out.txt textlog.tmp.txt >nul
    TYPE textlog.tmp.txt|repl.bat "#%%S$" "#!VARIABLE!" > textlog.out.txt
DEL textlog.tmp.txt
  • thanks for quick reply.. but i would only like to change " //packages/thirdparty/release/main.txt #10" and #10 can be anything. so lets assume #10 = #XX. and #15 comes from a variable.. can i use %VARIABLE%? – Mihir Mar 10 '15 at 20:21
  • that is cheating a little bit, because it's not pure batch and the question did say batch. Nevertheless, it is written by a king of batch, dave benham, so repl.bat is probably as batchy as one can get for this particular problem – barlop Mar 10 '15 at 20:27
  • From your link "REPL.BAT has been superceded by JREPL.BAT, available at viewtopic.php?f=3&t=6044. I am no longer maintaining REPL.BAT" – DavidPostill Mar 10 '15 at 22:22
  • Ya, that's why I like this one better. It isn't going to change later. If you want the newer one then use that. It is very similar. – krowe Mar 10 '15 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.