如何在文本文件中的特定行(最后一行)之前添加新行?

时间:2015-07-18 16:51:53

标签: windows batch-file command-line

假设我有一个 diskpart 脚本文件disk1.txt,其中包含:

list vol
exit

和批处理文件包含:

    @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

现在我想在最后一行之前的disk2.txt添加一行。

如何在最后一行之前添加新行?

如何在特定行之前添加新行,即在第4行或第3行之前,或任何其他指定的行?

1 个答案:

答案 0 :(得分:1)

这是一个简单的演示批处理代码,用于在文本文件中的特定位置插入一行:

@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

注意:这个简单的批处理代码不适用于包含没有字符或只有空格字符的行的源文件。换句话说,disk1.txt中的每一行必须包含至少1个非空白字符。

相关问题