Robby Johnston
Robby Johnston

Reputation: 191

Find and Replace from batch file not working

I am trying to find and replace values of a string within a batch file but having issues. I have the user run the batch file and it asks the user 1)what drive the file is on 2)what is the name of folder in the TEST parent folder 3)what is the name of the new server. I want the batch file to look within a file called importer.config and replace a value called server_name with whatever the input from the user is. Here is what I have:

@echo off
SET drive=
SET /P drive=Please enter the drive:

SET folder=
SET /P folder=Enter name of folder desired:

SET server=
SET /P server=Enter name of new server:

@echo off > newfile.txt
setLocal EnableDelayedExpansion

if exist newfile.txt del newfile.txt

for /f "tokens=* delims= " %%a in (%drive%\test\%folder%\importer.config) do (
set str=%%a
set str=!str:server_name=%server%!
echo !str! >> newfile.txt
)
del importer.config
rename newfile.txt importer.config

pause

Every time I run this, the cmd prompt shows: The system cannot find the file specified c:\test\users_input_they_entered\importer.config. The issue is that file is there so trying to understand what I am missing and why it cant find the file that does exist.

It then also states "Could not find c:\windows\system32\importer.config" which not sure why that happens as well

I have searched on stackoverflow, but cannot figure this out with any assistance.

Upvotes: 0

Views: 484

Answers (1)

You're pushing your luck using the for loop for that.

A tool like sed would work well.

If you look at this post they have a vbscript implementation that you could use Is there any sed like utility for cmd.exe

set input_file=importer.config
set output_file=temp.config
set new_server_name=server1984

cscript /Nologo sed.vbs s/server_name/%new_server_name%/ < %input_file% > %output_file%

Upvotes: 1

Related Questions