在txt文件中搜索一行并删除批处理文件中的后续13行

时间:2022-03-21 20:20:38

I have some txt files that I need a batch file to search for a specific line and then delete that line and the subsequent 13 lines from the txt file.

我有一些txt文件,我需要一个批处理文件来搜索特定的行,然后从txt文件中删除该行和后续的13行。

and example of the txt file is:

以及txt文件的示例是:

<section1>
line1
line2
line3

<section2>
line1
line2
line3
line4
line5

<section3>
line1
line2
line3
line4
line5
line6
line7
line8

etc.

The line i would need to search for is <section2> and then delete the following:

我需要搜索的行是 然后删除以下内容:

<section2>
line1
line2
line3
line4
line5

So ending up with:

最后得到:

<section1>
line1
line2
line3

<section3>
line1
line2
line3
line4
line5
line6
line7
line8

etc.

I would also need to edit some lines after the other sections, for example edit line1 in <section3> to say editline1

我还需要在其他部分之后编辑一些行,例如编辑 中的line1来表示editline1

So it would find the <section3> string and alter line 1 to appear as below

所以它会找到 字符串并改变第1行如下所示

<section3>
editline1
line2
line3
line4
line5
line6
line7
line8

Thanks

1 个解决方案

#1


0  

@echo off
  set fnam="%~1"
  set outnam="%~dpn1.out"
  set search4="%~2"
  set section=.
  for /f "tokens=*" %%x in ('type %fnam%') do call :work %fnam% "%%x"
  MOVE /Y %outnam% %fnam%
goto :eof

:work
  set "line=%~2"
  if "%line:~0,1%%line:~-1%"=="<>" (
    if "%section%" neq "." echo.>> %outnam%
    set "section=^%line:~,-1%^>"
    set "line=^%line:~,-1%^>"
  )
  if NOT "%section:~1,-2%>"==%search4% echo %line%>> %outnam%

Call it like this:

这样叫:

section filename.txt "<section2>"

#1


0  

@echo off
  set fnam="%~1"
  set outnam="%~dpn1.out"
  set search4="%~2"
  set section=.
  for /f "tokens=*" %%x in ('type %fnam%') do call :work %fnam% "%%x"
  MOVE /Y %outnam% %fnam%
goto :eof

:work
  set "line=%~2"
  if "%line:~0,1%%line:~-1%"=="<>" (
    if "%section%" neq "." echo.>> %outnam%
    set "section=^%line:~,-1%^>"
    set "line=^%line:~,-1%^>"
  )
  if NOT "%section:~1,-2%>"==%search4% echo %line%>> %outnam%

Call it like this:

这样叫:

section filename.txt "<section2>"