簡體   English   中英

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

[英]How can I add a new line before a specific line (last line) in text file?

假設我有一個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行或任何其他指定的行之前?

這是一個簡單的演示批處理代碼,用於在文本文件中的特定位置插入一行:

@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個非空白字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM