我有一个文本文件,其中有超过200行,我只是想在第4行之前添加一个新行。我正在使用Windows XP。
input前的示例文本文件:
header 1 header 2 header 3 details 1 details 2
输出后:
header 1 header 2 header 3 <----- This is new line ----> details 1 details 2
我相信你正在使用的
echo Text >> Example.txt
功能?
如果是的话,答案只不过是加一个“。”。 (点)后直接回声没有别的。
例:
echo Blah echo Blah 2 echo. #New line is added echo Next Blah
您可以使用:
type text1.txt >> combine.txt echo >> combine.txt type text2.txt >> combine.txt
或者像这样的东西:
echo blah >> combine.txt echo blah2 >> combine.txt echo >> combine.txt echo other >> combine.txt
免责声明:以下解决方案不保留尾随选项卡。
如果您知道文本文件中的确切行数,请尝试以下方法:
@ECHO OFF SET origfile= original file SET tempfile= temporary file SET insertbefore=4 SET totallines=200 <%origfile% (FOR /L %%i IN (1,1,%totallines%) DO ( SETLOCAL EnableDelayedExpansion SET /PL= IF %%i==%insertbefore% ECHO( ECHO(!L! ENDLOCAL ) ) >%tempfile% COPY /Y %tempfile% %origfile% >NUL DEL %tempfile%
循环从原始文件中逐行读取并输出。 输出被重定向到一个临时文件。 当到达某一行时,在它之前输出一个空行。
完成后,原始文件将被删除,临时文件将被分配原始名称。
UPDATE
如果行数未知,则可以使用以下方法获取:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(这一行简单地替换上面的脚本中的SET totallines=200
行。)
该方法有一个小小的缺陷:如果文件以空行结束,结果将是实际的行数减一。 如果您需要解决方法(或者只是想安全玩),您可以使用此答案中描述的方法。
假设你想插入一行文本(不是空行):
@echo off FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C set /a totallines+=1 @echo off <%origfile% (FOR /L %%i IN (1,1,%totallines%) DO ( SETLOCAL EnableDelayedExpansion SET /p L= IF %%i==%insertat% ECHO(!TL! ECHO(!L! ENDLOCAL ) ) >%tempfile% COPY /Y %tempfile% %origfile% >NUL DEL %tempfile%