0

I want to insert a string of text say "hello" in a particular line say n (12 or 23 or some other number) using batch script. I know batch script is bad but unfortunately the requirement for this is batch script.

Here's what I've tried

@echo off
setlocal enableextensions disabledelayedexpansion
set "nthline=TEXT"
(for /f "usebackq tokens=* delims=" %%a in (c.txt) do (
    echo(%%a
    if defined nthline ( 
        echo(%nthline%
        set "nthline="
    )
))

This code I got from here but it only inserts to the second line I cannot make it go beyond that.

Here is what the text file contains

aaaa
bbbb
cccc
dddd
ffff
gggg
hhhh 

It inserts the string after aaaa. How can I make it insert at bbbb or ffff I'm new to batch scripting so Any help is greatly appreciated

aschipfl
  • 31,767
  • 12
  • 51
  • 89
Death Guard
  • 362
  • 3
  • 14

1 Answers1

2

The code you have posted is designed to insert an extra line after the first one.

To insert at a certain point you need to somehow predefine the target line number and a line number, then compare these numbers for equality and return the extra line of text ‐ line in the following script:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constante here:
set "_FILE=c.txt" & rem // (text file to insert a line of text into)
set "_TEXT=hello" & rem // (text of the inserted line)
set /A "_NUM=4"   & rem // (number of the line where the new line is inserted)
set "_REPLAC=#"   & rem // (set to anything to replace the target line, or to nothing to keep it)
set "_TMPF=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (path and name of temporary file)

rem // Write result into temporary file:
> "%_TMPF%" (
    rem // Loop through all lines of the text file, each with a preceding line number:
    for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
        rem // Store current line including preceding line number to a variable:
        set "LINE=%%L"
        rem // Set the current line number to another variable:
        set /A "LNUM=%%L"
        rem // Toggle delayed expansion to avoid trouble with `!`:
        setlocal EnableDelayedExpansion
        rem // Compare current line number with predefined one:
        if !LMUN! equ %_NUM% (
            rem // Line numbers match, so return extra line of text:
            echo(!_TEXT!
            rem // Return original line (without preceding line number) only if it is not to be replaced:
            if not defined _REPLAC echo(!LINE:*:=!
        ) else (
            rem // Line numbers do not match, so return original line (without preceding line number) anyway:
            echo(!LINE:*:=!
        )
        endlocal
    )
)
rem // Move temporary file onto original one:
move /Y "%_TMPF%" "%_FILE%"

endlocal
exit /B
aschipfl
  • 31,767
  • 12
  • 51
  • 89
  • @ Prabhjot Singh Kainth linked the answer in the first comment that seemed to work and it's almost the same as your code. – Death Guard Dec 05 '19 at 04:59