如何在文本文件中查找单词并删除包含单词和后两行的行?

时间:2015-09-12 05:21:21

标签: batch-file replace

我想使用批处理文件在文本文件中找到一个单词,然后我想删除包含该单词的那一行,并删除下面的其他一些行,例如:

_italic_ or **bold**
put returns between paragraphs
indent code by 4 spaces
indent code by 4 spaces
_italic_ or **bold**2

所以结果应该是:

_italic_ or **bold**
_italic_ or **bold**2

3 个答案:

答案 0 :(得分:2)

您可以尝试以下批处理代码:

@echo off
set skipline=2
set search=returns
set File=Input.txt
setlocal EnableDelayedExpansion
for %%a in ("%File%") do (
    set linecount=1
    set skip=0
    For /f "usebackq tokens=* delims=" %%b IN (`type "%%a" ^| find /V /N ""`) do (
        set a=%%b
        set a=!a:*]=!
        if "!a!" NEQ "" (
            set search=!a:%search%=!
            if "!search!" NEQ "!a!" set /a skip=%skipline%+!linecount!
        )
        if !linecount! GTR !skip! echo(!a!
        set /a linecount+=1

    )>>tmp
    move /Y "tmp" "%%a">Nul
)
EndLocal
exit

这适用于包含空行和多行的文件。

更改设置skipline = 2 ,查找您搜索的单词后要跳过的行数。

对于多个文件,只需更改设置File = Input.txt

当前目录中扩展名为 .txt 的文件示例:

set File=*.txt

答案 1 :(得分:1)

@echo off
setlocal EnableDelayedExpansion

rem Get the number of lines before the one that contain "returns"
for /F "delims=:" %%a in ('findstr /N "returns" input.txt') do set /A "lines=%%a-1"

rem Open a code block to read from input.txt and write to output.txt
< input.txt (

   rem Read and write the first "lines" lines
   for /L %%i in (1,1,%lines%) do (
      set "line="
      set /P "line="
      echo(!line!
   )

   rem Omit the number of desired lines (3 in this example)
   for /L %%i in (1,1,3) do set /P "line="

   rem Copy the rest of lines
   findstr "^"

) > output.txt

rem Replace the original file by the new one
move /Y output.txt input.txt

答案 2 :(得分:0)

此任务的批处理代码仅适用于不包含空行的输入文本文件,因为命令 FOR 会跳过这些行。

它会移除所有块3行,第一行包含returns

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SkipLineCount=0"
set "OutputFile=OutputTextFile.txt"
del "%OutputFile%" 2>nul
for /F "usebackq eol=^ delims=" %%I in ("InputTextFile.txt") do (
    if !SkipLineCount! EQU 0 (
        set "Line=%%I"
        set "Line=!Line:returns=!"
        if "!Line!" NEQ "%%I" ( set "SkipLineCount=1" ) else echo(%%I>>"%OutputFile%"
    ) else (
        set /A SkipLineCount+=1
        if !SkipLineCount! EQU 3 set "SkipLineCount=0"
    )
)
move /Y "%OutputFile%" "InputTextFile.txt"
endlocal

此批处理文件处理每个非空行。命令 FOR 会自动跳过所有不包含任何字符的行。

注1:eol=^符合命令 FOR ,需要读入并输出只包含逗号或分号的行,否则命令 FOR < /强>

如果当前不应跳过任何行,则将当前行分配给变量Line。接下来,如果该行包含至少一个returns,则所有出现的单词returns都会从行中删除不区分大小写。

如果字符串替换后的变量Line的字符串不相等而忽略该行,则从文件中读取未修改的行,因为这意味着该行至少包含一个returns

否则从输入文件读取的行将附加到输出文件。

注意2:(echo之间的%%I用于输出仅包含1个或多个空格或制表符的输入行,否则输出空格而不是{{1}命令 echo 会为这种情况写入当前状态(到输出文件中,而不是从输入文件中读取的空格/标签。

至少有一个OFF的行之后的下两行也会被忽略,无法复制到输出文件。

作为最后一个命令,删除了3行的创建输出文件将移动到输入文本文件中。

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • returns
  • del /?
  • echo /?
  • for /?
  • if /?
  • move /?
  • set /?

另请阅读Microsoft有关Using Command Redirection Operators

的文章