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?
4 Answers
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).

- 24,511
- 12
- 71
- 99
-
Can you explain your solution? What is the filename in your example? And what do you edit exactly? And if you just edit in the line 2, why do you have a loop? – akcasoy Oct 29 '13 at 17:20
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.

- 1
- 1

- 5,425
- 2
- 31
- 40
-
And to Finish, you can use the environment variable substring replacement functionality. e.g. "ECHO %OLDLINE:cat=dog&" If you have delayed expansion enabled, you can even "ECHO %OLDLINE:cat=!var!%" – Steven Dec 05 '08 at 14:39
This would be ugly to do with native batch scripting. I would either
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.
Use a sed script. There are windows ports of Unix commands like GnuWin32, GNU Utilities for Win32 (I use these), or Cygwin.

- 28,540
- 12
- 67
- 94
I would create a script that would:
- scan the input file
- write to a second output file
- delete the input
- 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)

- 10,944
- 6
- 56
- 81
-
-
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 Dec 05 '08 at 14:23
-
You hippies =) I just felt guilty stealing code freely posted on the internets. – Kieveli Dec 05 '08 at 14:54
-
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 Dec 05 '08 at 14:56