用于删除特定行号的批处理文件

时间:2014-10-08 11:40:52

标签: batch-file line lines

我有一个文件每24小时更新一次,新数据添加到最后(应该如此),但文件开头的一些数据变得无关紧要。我需要的是一个删除第3行和第4行的批处理文件,然后使用相同的名称保存文件。

所以,例如,假设文件是​​file.txt,它看起来像这样:

  1. A
  2. C
  3. d
  4. 电子
  5. ˚F
  6. 我需要删除第3行和第4行,因此文件现在看起来像这样:

    1. A
    2. 电子
    3. ˚F
    4. 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

以下是通过删除第3行和第4行来修改文件的批处理代码。

完全评论。所以我希望你理解它。

您需要在第五行修改要修改的文件的路径和名称。

@echo off
setlocal EnableDelayedExpansion

rem Define name of file to modify and check existence.
set "FileToModify=C:\Temp\Test.tmp"
if not exist "%FileToModify%" goto EndBatch

rem Define name of temporary file and delete this file if it currently
rem exists for example because of a breaked previous batch execution.
set "TempFile=%TEMP%\FileUpdate.tmp"
if exist "%TempFile%" del "%TempFile%"

rem Define a line number environment variable for temporary usage.
set "Line=0"

rem Process the file to modify line by line whereby empty lines are
rem skipped by command FOR and all other lines are just copied to
rem the temporary file with the exception of line 3 and line 4.
for /F "useback delims=" %%L in ("%FileToModify%") do (
    if !Line! GTR 3 (
        echo %%L>>"%TempFile%"
    ) else (
        rem Increment line number up to number 4.
        set /A Line+=1
        rem Copy line 1 and 2, but not line 3 and 4.
        if !Line! LSS 3 echo %%L>>"%TempFile%"
    )
)

rem Copy the temporary file being a copy of file to modify with
rem the exception of removed line 3 and 4 over the file to modify.
rem Finally delete the temporary file.
copy /Y "%TempFile%" "%FileToModify%" >nul
del "%TempFile%"

:EndBatch
endlocal
相关问题