Вот чистая пакетная реализация вашей стратегии. Код сильно комментируется, чтобы объяснить, как он работает. Код должен работать так же хорошо, как пакетные сценарии go. Небольшие изменения в формате исходного файла могут легко испортить код, но это неотъемлемый риск для вашего дизайна.
@echo off
setlocal
set "input=file.txt"
set "output=output.txt"
set "tempFile=find.txt"
:: Prepare find.txt containing all the line numbers that should be excluded.
:: Each line consists of a line number followed by a colon.
:: The findstr lists the lines that contain one of the search terms, with the
:: line number followed by colon as a prefix.
:: The FOR /F parses the results to get the line numbers.
:: The DO clause computes the begin and end values and iterates all values
:: in between so can echo to the find.txt file.
::
setlocal enableDelayedExpansion
>"%tempFile%" (
for /f "delims=:" %%N in ('findstr /n "\<toto\> \<tata\>" "%input%"') do (
set /a "beg=%%N-2, end=%%N+2"
for /l %%N in (!beg! 1 !end!) do echo %%N:
)
)
endlocal
:: The first FINDSTR prefixes each line with the line number followed by a colon.
:: The second FINDSTR excludes all the line numbers specified in find.txt.
:: The FOR /F parses the result and strips the line number prefix so can output
:: the final result.
::
>"%output%" (
for /f "delims=: tokens=1*" %%A in (
'findstr /n "^" "%input%" ^| findstr /vbig:"%tempFile%"'
) do @echo(%%B
)
del "%tempFile%"
Ниже приведен один вкладыш, использующий утилиту обработки текста с регулярными выражениями под названием JREPL. BAT . Это должно быть более надежным, поскольку распознает только tata или toto в элементе <Key>
. Он также не заботится о том, где появляются новые строки.
jrepl "[\s\S]*<Key>(toto|tata)</Key>[\s\S]*" "" /m /p "<KeyValuePairs>[\s\S]*?</KeyValuePairs>\r?\n?" /f test.txt /o output.txt
Поскольку сам JREPL является пакетным скриптом, вам нужно будет использовать CALL JREPL
, если вы поместите команду в пакетный скрипт.