我需要能够提取文本文件中两个空白行之间的部分。文本文件看起来像这样...
This is line 01 of the text file.
This is line 02 of the text file.
This is line 03 of the text file.
This is line 05 of the text file.
This is line 06 of the text file.
This is line 07 of the text file.
> VALUE TO SEARCH <
This is line 09 of the text file.
This is line 10 of the text file.
This is line 12 of the text file.
This is line 13 of the text file.
因此,我可以在文本文件中搜索并找到“> 要搜索的值 <”,但随后我需要能够抓取到该节的前一个空白行和尾随空白行为止的所有内容。这有意义吗?无论如何,每个节的行数各不相同,但各节之间总是有一个空白行。
可以通过批处理文件完成吗?如果可以,怎么做?
提前致谢!
答案1
纯 Windows 批处理不太适合文本处理。
我会用我的JREPL.BAT 正则表达式文本处理实用程序jrepl /?
完成这项任务。它是纯脚本(混合 JScript/批处理),可在 XP 及以上版本的任何 Windows 机器上本地运行。通过从命令行执行可获得完整文档。
这是使用 JREPL.BAT 的解决方案。请注意,搜索是正则表达式,因此您必须转义 VALUE TO SEARCH 中的正则表达式元字符的搜索字符。该命令读取“test.txt”并将结果写入“out.txt”
jrepl "([^\r\n]+\r?\n)*.*VALUE TO SEARCH.*\n?([^\r\n]+\r?\n?)*" "$0" /jmatch /m /f test.txt /o out.txt
CALL JREPL
如果将该命令放在批处理脚本中,则必须使用。
可以使用纯批处理来解决这个问题,但它很复杂,效率低得多(慢得多)。这是一个解决方案。
@echo off
setlocal enableDelayedExpansion
set "infile=test.txt"
set "outfile=out.txt"
set "find=VALUE TO SEARCH"
set "emptyFile=empty.txt"
:: Compute end of file as number of lines + 1
for /f %%N in ('find /c /v "" ^<"%infile%"') do set /a last=%%N+1
:: Get list of line numbers of empty lines and append end of file
>"%emptyFile%" (
for /f "delims=:" %%N in ('findstr /n "^$" "%infile%"') do echo %%N
echo !last!
)
<"%infile%" >"%outFile%" (
set /a last=1
%= iterate list of found line numbers, ignoring lines that have already been printed =%
for /f "delims=:" %%A in ('findstr /nc:"!find!" "!infile!"') do if %%A geq !last! (
%= Locate beginning and end of found section, and compute lines to skip =%
set /a beg=0
set "end="
for /f "usebackq" %%B in ("%emptyFile%") do if not defined end (
if %%B gtr %%A (set /a end=%%B, start=beg+1, stop=end-1) else set beg=%%B
)
%= Skip lines until beginning of found section =%
for /l %%N in (!last! 1 !beg!) do set /p "ln="
%= Write empty line delimiter if not first found section =%
if !last! gtr 1 (echo()
%= Read and write found section =%
for /l %%N in (!start! 1 !stop!) do (
set /p "ln="
(echo(!ln!)
)
set /a last=end
)
)
del "%emptyFile%"
上述纯批处理解决方案有以下局限性:
- 行长必须小于等于 1021 字节
- 每行末尾的控制字符将被删除
- 每行必须以 (Windows 风格) 结束
\r\n
。它不适用于\n
(Unix 风格)。