有什么方法可以用来findstr
搜索:
<char>Hello there my friend,</char>
<continued>this is two lines of text</continued>
我需要搜索包含第二行的字符串。我尝试过类似这样的方法:
@echo off
setlocal enableDelayedExpansion
set file=test.txt
set LF=^
:: The above 2 blank lines MUST be preserved!
findstr /RC:"hello!LF!there" "test.txt" >nul
if %errorlevel%==0 echo found 1!
pause
其中 test.txt 包含:
oh
hello
there
friends
how are
you
但它没有被触发。
答案1
查找是否有匹配项
@echo off
setlocal enableDelayedExpansion
set file=test.txt
set line1=hello
set line2=there
set LF=^
:: The above 2 blank lines MUST be preserved!
:: Define a CR variable as a CarriageReturn (0x0D) character
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
cmd /v:on /c^"findstr /rc:"%line1%^!CR^!*^!LF^!%line2%" %file%^" >nul
if %errorlevel%==0 echo found at least 1!
pause
此批处理文件添加了对回车符的检查,这对于带有 Windows 样式换行符 ( CR LF
) 的文本文件是必需的。它还在启用延迟扩展的findstr
单独cmd
进程中运行。这似乎是必要的,即使已经启用了延迟扩展。
最后,这包括两个变量:line1
和line2
,它们可以编辑。这使文件更易于阅读,以便将来编辑。您还可以在其中包含相同的正则表达式变量,因此hell.
将匹配hello
等。
查找匹配项的数量
@echo off
setlocal enableDelayedExpansion
set file=test.txt
set line1=hell.
set line2=there
set LF=^
:: The above 2 blank lines MUST be preserved!
:: Define a CR variable as a CarriageReturn (0x0D) character
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
set results=0
for /f %%a in ('cmd /v:on /c^"findstr /rc:"%line1%^!LF^!%line2%" %file%^"') do set /A results+=1
echo found %results%!
pause
这里显著的区别是for /f
围绕搜索的和,每找到一个匹配项,set /A results+=1
它就会将变量加 1 。results