我刚刚开始尝试使用MS Batch文件。我创建了一个小批处理,使用findstr / m在输入的目录中搜索包含特定字符串的文件。它返回一个包含字符串的文件,但只返回它找到的第一个字符串。我搜索过findstr /?和在线命令参考,以及本网站。我找不到一种方法让findstr返回带有字符串实例的所有文件。我错过了什么?
@echo off
setlocal
ECHO This Program Searches for words inside files!
:Search
set /P userin=Enter Search Term:
set /p userpath=Enter File Path:
FOR /F %%i in ('findstr /M /S /I /P /C:%userin% %userpath%\*.*') do SET finame=%%i
if "%finame%" == "" (set finame=No matching files found)
echo %finame%
set finame=
endlocal
:searchagain
set /p userin=Do you want to search for another file? (Y/N):
if /I "%userin%" == "Y" GOTO Search
if /I "%userin%" == "N" GOTO :EOF ELSE (
GOTO wronginput
)
Pause
:wronginput
ECHO You have selected a choice that is unavailable
GOTO searchagain
答案 0 :(得分:1)
如果你替换它:
FOR /F %%i in ('findstr /M /S /I /P /C:%userin% %userpath%\*.*') do SET finame=%%i
if "%finame%" == "" (set finame=No matching files found)
echo %finame%
set finame=
然后它可能会按照你期望的方式工作
findstr /M /S /I /P /C:"%userin%" "%userpath%\*.*"
if errorlevel 1 echo No matching files found
答案 1 :(得分:0)
在你的for循环中,当你为finame分配%% i的值时,你正在替换之前的值,所以只有最后一个文件被回显到控制台。
如果您尝试使用findstr命令(在for之外),您将看到文件列表。
答案 2 :(得分:0)
将所有内容放在var:
中setlocal enabledelayedexpansion
set nlm=^
set nl=^^^%nlm%%nlm%^%nlm%%nlm%
for %%i in ('dir %userpath% /b') do for /f %%a in ('type "%userpath%\%%i"^|find "%userin%" /i') do set out=!out!!nl!%%i
答案 3 :(得分:0)
谢谢大家。如果其他人搜索此网站,这是我的最终代码。
@echo off
ECHO This Program Searches for words inside files!
:Search
setlocal
set /P userin=Enter Search Term:
set /p userpath=Enter File Path:
findstr /M /S /I /P /C:%userin% %userpath%\*.* 2> NUL
if ERRORLEVEL 1 (ECHO No Matching Files found) ELSE (
GOTO searchagain
)
endlocal
:searchagain
setlocal
set /p userin=Do you want to search for another file? (Y/N):
if /I "%userin%" == "Y" GOTO Search
if /I "%userin%" == "N" GOTO :EOF ELSE (
GOTO wronginput
)
endlocal
:wronginput
ECHO You have selected a choice that is unavailable
GOTO searchagain