Search code examples
vbscriptbatch-fileedittext-fileslines

Find the line & edit it


I posted another one on this,, but i had to edit it really much...

What the thing bassicly is that a Batch (Maybe including VBScript) can find line 29 in a txtfile... it should edit this line.

If line 29 is like this: 'option=21' it should change it to 'option=22'

the problem is that this line is located more in the file. so it should just edit line 29...

How-to???

[please no custom programs;;; it should be done by every user without installing something OK.]


Solution

  • This isn't something you're usually doing in batch, but it's fairly straightforward:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    
    rem the input file
    set inputfile=file.txt
    
    rem temporary file for output, we can't just write into the
    rem same file we're reading
    set tempfile=%random%-%random%.tmp
    
    rem delete the temporary file if it's already there
    rem shouldn't really happen, but just in case ...
    copy /y nul %tempfile%
    
    rem line counter
    set line=0
    
    rem loop through the file
    for /f "delims=" %%l in (%inputfile%) do (
        set /a line+=1
        if !line!==29 (
            rem hardcoded, at the moment, you might want to look
            rem here whether the line really starts with "options"
            rem and just put another number at the end.
            echo option=22>>%tempfile%
        ) else (
            echo %%l>>%tempfile%
        )
    )
    
    del %inputfile%
    ren %tempfile% %inputfile%
    
    endlocal
    

    It should point you into the general direction if you want to adapt it.