不知道這是否是必需的,但我開發的解決方案允許匹配組在輸入文件中多次出現。每個解決方案保留匹配組的所有實例。
對於下面的代碼,我假設的數據是「input.txt中」,輸出是「output.txt的」
這裏是純一批表現相當不錯簡單的批處理代碼去:
@echo off
setlocal disableDelayedExpansion
set "print="
(for /f "delims=" %%A in (input.txt) do (
if defined print for /f "delims=1" %%B in ("%%A") do if "%%B" equ "B" set "print="
if not defined print for /f %%B in ("%%A") do if "%%B" equ "B10119628000D5" set print=1
if defined print echo %%A
)) >output.txt
如果文件非常大,上面的內容可能會變得很慢。
我寫了一個hybrid JScript/batch utility called REPL.BAT,可以用來製作一個非常有效的更簡單的解決方案。 REPL.BAT是純粹的腳本,它可以從XP以後的任何現代Windows機器上本機運行。完整的文檔嵌入在腳本中。
我使用REPL.BAT將不在「B1」前面的換行符編碼爲「@」,從而將一組行換成一行。然後FINDSTR被用來只保留所需的行(匹配「組」),最後一個REPL.BAT將「@」解碼回新行。如果數據可能包含「@」,則替換數據中不存在的其他字符。
type input.txt|repl \n(?!B1) @ m|findstr /bc:"B10119628000D5 "|repl @ \n x >output.txt
如果你找不到不存在數據,然後「@」可以通過另一輪的編碼和解碼的被保護的角色:
type input.txt|repl @ @a|repl \n(?!B1) @n m|findstr /bc:"B10119628000D5 "|repl @n \n x|repl @a @ >output.txt
如果在搜索字符串過濾器之後不需要空格,按照註釋,則解決方案更改如下:
選項1:
@echo off
setlocal enableDelayedExpansion
set "print="
(for /f "delims=" %%A in (input.txt) do (
set "ln=%%A"
if defined print if "!ln:~0,2!" equ "B1" set "print="
if not defined print if "!ln:~0,14!" equ "B10119628000D5" set print=1
if defined print echo %%A
)) >output.txt
選項2:
type input.txt|repl \n(?!B1) @ m|findstr /b B10119628000D5|repl @ \n x >output.txt
選項3:
type input.txt|repl @ @a|repl \n(?!B1) @n m|findstr /b B10119628000D5|repl @n \n x|repl @a @ >output.txt
你想發現,在一定值開始(比如'B10119628000D5')線和顯示從它開始的5行的組?可能是幾個以相同價值開始的小組? – Aacini