MS DOS edit the file

I am writing a batch script that I want to open and then change the second line. I want to find the string "cat" and replace it with the value I have SET ie% var%. I want this to happen on the second line (or the first 3 times). How would you do it?

0


source to share


4 answers


I just solve it myself. It will only search for var on line 2.

@echo OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET filename=%1
set LINENO=0    
for /F "delims=" %%l in (%filename%) do (
 SET /A LINENO=!LINENO!+1
 IF "!LINENO!"=="2" ( call echo %%l ) ELSE ( echo %%l )
)

      



But I prefer to use cscript (vbscript or even jscript).

+1


source


First of all, using a batch file to accomplish this is messy (IMHO). You will have to use an external tool to replace the string anyway. I would use a scripting language instead.



If you really want to use the package, this one will get you started.

0


source


It would be ugly if done with scripts with the original package. I would either

  • Do it in VBScript. If you really need it in a batch file, you can call the VBScript file from within the batch script. You can even pass% var% as an argument to VBScript.

  • Use a sed script. There are Unix command window ports such as GnuWin32 , GNU Utilities for Win32 (which I use), or Cygwin .

0


source


I would create a script that:

  • scan input file
  • write to second output file
  • delete entry
  • rename output

As far as dos commands for parsing are concerned, I did Google Search and came up with a good starting point:

@echo off
setlocal enabledelayedexpansion

set file=c:\file.txt
set output=output.txt
set maxlines=5000

set count=0

for /F "tokens=* usebackq" %%G in ("%file%") do (
 if !count!==%maxlines% goto :eof

 set line=%%G
 set line=!line:*000000000000=--FOUND--!
 if "!line:~0,9!"=="--FOUND--" (
  echo %%G>>"%output%"
  set /a count+=1
 )
)

      

(stolen from Intarwebnet)

-2


source







All Articles