1

i have created a .cmd file which takes file name as argument then it asks for string to find and then string to replace.

desired out put

findthis should be replaced from given file with replacewith but it is not working

following is code which i have tried..

@echo off
setlocal enabledelayedexpansion

if not exist "%1" (echo this file does not exist...)&goto :eof

set /p findthis=find this text string:
set /p replacewith=and replace it with this:


for /f "tokens=*" %%a in (%1) do (

   set write=%%a
   if %%a==%findthis% set write=%replacewith%

   echo !write! 
   echo !write! >>%~n1.replaced%~x1
)

thanks

Mark
  • 3,609
  • 1
  • 22
  • 33
Jagtap C. V.
  • 11
  • 1
  • 5

1 Answers1

0

There are a couple of simple bugs in your code that I have fixed. You should put the strings in quotes as they are very likely to contains spaces. Sometimes they may be a null string which causes problems with echo, so I've added a ";" to the echo to deal with that:

@echo off
setlocal enabledelayedexpansion

if not exist "%1" (echo this file does not exist...)&goto :eof

set /p findthis=find this text string:
set /p replacewith=and replace it with this:


for /f "tokens=*" %%a in (%1) do (

   set write=%%a
   if "%%a"=="%findthis%" set write=%replacewith%

   echo;!write! 
   echo;!write! >>%~n1.replaced%~x1
)

However, this only can match and replace whole line, and not a text string within a line. To replace a substring within a line you have to use the variable string replace syntax (which is cited several times in questions: here and finally here.

The latter answer contains everything you need to solve your original problem.

Community
  • 1
  • 1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129