Reputation: 565
Suppose I have a diskpart script file disk1.txt
containing:
list vol
exit
and batch file which contains:
@echo off
pushd %~dp0
diskpart /s disk1.txt
set /p vol=enter number of the volume
echo sel vol %vol% > disk2.txt
type disk1.txt >> disk2.txt
diskpart /s disk2.txt
del disk2.txt
pause
Now I want to add a line in disk2.txt
before the last line.
How can I add the new line before the last line?
And how can I add a new line before a specific line, i.e. before line 4 or line 3, or any other specified line?
Upvotes: 1
Views: 1974
Reputation: 49097
Here is a simple demo batch code for inserting a line at a specific position within a text file:
@echo off
setlocal EnableDelayedExpansion
rem A negative value inserts a line X lines before last line of source file.
rem A positive value inserts a line before line X from source file.
rem Value 0 assigned to InsertBeforeLine results in a copy of source file.
set "InsertBeforeLine=-1"
if %InsertBeforeLine% LSS 0 (
set "LineCount=1"
for /F "usebackq eol= delims=" %%L in ("disk1.txt") do set /A "LineCount+=1"
set /A "InsertBeforeLine+=LineCount"
)
set "LineCount=1"
for /F "usebackq eol= delims=" %%L in ("disk1.txt") do (
if %InsertBeforeLine% EQU !LineCount! echo Inserted line>>disk2.txt
echo %%L>>disk2.txt
set /A "LineCount+=1"
)
endlocal
Note: This simple batch code does not work for a source file containing lines with no characters or only whitespace characters. In other words each line in disk1.txt
must contain at least 1 non whitespace character.
Upvotes: 1