How to make a BAT to edit a string inside a test file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
keropi
Posts: 5
Joined: 27 Feb 2010 18:36
Location: Greece

How to make a BAT to edit a string inside a test file?

#1 Post by keropi » 27 Feb 2010 18:41

Hiya!

Let me explain what I want to do...
I am trying to make a DOS-only batch file that will edit a variable in a text file , the variable depends on the location of the .bat file...
so for example if I have:
c:\test\varedit.bat
it would open a file , look for a predefined string like %EDITME% and change it to C:\TEST\
I know I can get to a dos variable the current .bat file location with %~dp0 , but how to make %~dp0 replace the %EDITME% string in my file?
any pointers would be highly appreciated! :mrgreen:

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to make a BAT to edit a string inside a test file?

#2 Post by aGerman » 28 Feb 2010 15:09

Code: Select all

@echo off &setlocal
set file=test.txt
set replacevar=%%editme%%

type nul>"temp.txt"
for /f "delims=: tokens=1*" %%a in ('findstr /n /r /c:"^" "%file%"') do set "line=%%b" &call :process
move "temp.txt" "%file%"
goto :eof
:: end of main


:process
if not defined line (
  >>"temp.txt" echo.
  goto :eof
)
set "line=%line:^=^^%"
set "line=%line:&=^&%"
set "line=%line:<=^<%"
set "line=%line:>=^>%"
set "line=%line:|=^|%"
setlocal enabledelayedexpansion
set "line=!line:%replacevar%=%~dp0!"
endlocal &>>"temp.txt" echo %line%
goto :eof


Note that you have to use %%EDITME%% instead of %EDITME%.

Regards
aGerman

keropi
Posts: 5
Joined: 27 Feb 2010 18:36
Location: Greece

Re: How to make a BAT to edit a string inside a test file?

#3 Post by keropi » 28 Feb 2010 17:04

thanks but it did not work... I should have pointed that I am using a DOS-only enviroment from win98se....

I get a "Syntax error" after: for /f "delims=: tokens=1*" %%a in ('findstr /n /r /c:"^" "%file%"') do set "line=%%b" &call :process

and the resulting test.txt is a 0 byte file (previous it only had some random line with %%EDITME%% in the end) is there a trick to do it in such an old DOS version?

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to make a BAT to edit a string inside a test file?

#4 Post by aGerman » 28 Feb 2010 18:10

You could try beginning your code with

Code: Select all

@echo off &setlocal ENABLEEXTENSIONS

also for your other thread.
But surely you need cmd.exe and afaik it's available on Win NT and higher versions.

Regards
aGerman

Post Reply