views:

837

answers:

4

I am writing a batch script which I wish to open a file and then change the second line of it. I want to find the string "cat" and replace it with a value that I have SET i.e. %var% . I only want this to happen on the second line (or for the first 3 times). How would you go about doing this?

A: 

First of all, using a batch file to achieve this, is messy (IMHO). You will have to use an external tool anyway to do the string replacement. I'd use some scripting language instead.

If you really want to use a batch, this will get you started.

Vincent Van Den Berghe
Steven
A: 

I would create a script that would:

  1. scan the input file
  2. write to a second output file
  3. delete the input
  4. rename the output

As far as the dos commands to parse, I did a 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 teh Intarwebnet)

Kieveli
c'mon.. how the heck can you link to experts exchange from SO? :)
Steven
Down vote for a link to Experts Exchange. The whole point of SO is to have a place you can go for help without having to log in to get answers.
Patrick Cuff
-1: ditto @Patrick Cuff
Ken Gentle
You hippies =) I just felt guilty stealing code freely posted on the internets.
Kieveli
Mind you.. this isn't to say that batch files are the best place for doing this kind of thing... I would probably write an easy C file to do it for me. Or if I had cygwin installed, any number of scripting languages.
Kieveli
A: 

This would be ugly to do with native batch scripting. I would either

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

  2. Use a sed script. There are windows ports of Unix commands like GnuWin32, GNU Utilities for Win32 (I use these), or Cygwin.

Patrick Cuff
+1  A: 

I just solve it myself. It will lookup var on line two only.

@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 using cscript (vbscript or even jscript).

Dennis Cheung