因此,當您使用批處理檔案在文本檔案中搜索子字串時,您可以使用如下內容:
:SearchOne
findstr %~1 %~2 >> output.txt
exit /b 0
如果您有多個搜索引數(都必須匹配...),您可以使用:
:SearchTwo
findstr %~1 %~2 | findstr %~3 >> output.txt
exit /b 0
如何搜索多個數字不固定的搜索鍵?
例如:
3:findstr %~1 %~2 | findstr %~3 | findstr %~4 >> output.txt
4:findstr %~1 %~2 | findstr %~3 | findstr %~4 | findstr %~5 >> output.txt
等等...?
uj5u.com熱心網友回復:
批處理檔案幾乎不可能在環境變數中建立管道。通過臨時檔案傳遞結果當然可以做到這一點。請注意,我假設您首先需要檔案名,如multifind *.cpp word1 word2 word3. 你擁有它的方式需要你寫那個multifind word1 *.cpp word2 word3,這似乎不自然。
@echo off
findstr %2 %1 > t001
shift
shift
if "%1" == "" goto doit
:loop
findstr %1 t001 > t002
del t001
ren t002 t001
shift
if not "%1" == "" goto loop
:doit
type t001
del t001
uj5u.com熱心網友回復:
在以下腳本中,第一個引數被視為要搜索的檔案:
@echo off
setlocal EnableDelayedExpansion
set "FILE=" & set "SEARCH="
rem /* Get file name from the very first command line argument; moreover,
rem put together a space-separated list of quoted search expressions: */
for %%A in (%*) do if defined FILE (set SEARCH=!SEARCH! "%%~A") else set "FILE=%%~A"
rem // Search the file for one expression at a time and overwrite it in each iteration:
if defined SEARCH for %%S in (!SEARCH!) do (
findstr "%%~S" "!FILE!" > "!FILE!.tmp" & move /Y "!FILE!.tmp" "!FILE!" > nul
)
endlocal
這不是絕對安全的,一些引數字串可能會導致語法錯誤。
uj5u.com熱心網友回復:
當搜索字串沒有引號時,這種非常簡單的方法可以正常作業,例如您的示例:
@echo off
setlocal
for /F "tokens=1,2*" %%a in ("%*") do set "string1=%%b" & set "rest=%%a %%c"
findstr "%string1%" "%rest: =" | findstr "%" >> output.txt
為了欣賞這里使用的技巧,洗掉該@echo off行并運行程式。一個例子如下所示:
C:\Tests> multifind.bat file.txt one two three four
C:\Tests> findstr "one" "file.txt" | findstr "two" | findstr "three" | findstr "four" 1>>output.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428993.html
標籤:批处理文件
