textbatch-file

Write batch variable into specific line in a text file


I have a batch file where I need to write a variable into a specific line of a text file and override what is all ready in that line. I have the code to read specific lines from the file maybe I could switch it around to also write?

Reading lines code:

setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (variables.txt) do (
set /a N+=1
set v!N!=%%a
)
set variable1=!v1!
set variable2=!v2!
set variable3=!v3!
set variable4=!v4!

I've tried to add echo %variable1% > !v4! something like that but it doesn't work.


Solution

  • I figured it out!! Here is the code for anyone else who might ever need it.

    @echo off
    setlocal enableextensions enabledelayedexpansion
    
    set inputfile=variables.txt
    
    set tempfile=%random%-%random%.tmp
    
    copy /y nul %tempfile%
    
    set line=0
    
    for /f "delims=" %%l in (%inputfile%) do (
        set /a line+=1
        if !line!==4 (
            echo WORDS YOU REPLACE IT WITH>>%tempfile%
        ) else (
            echo %%l>>%tempfile%
        )
    )
    
    del %inputfile%
    ren %tempfile% %inputfile%
    
    endlocal