1

我刚刚开始接触 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
4

4 回答 4

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
于 2013-10-24T14:43:57.040 回答
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
于 2013-10-25T20:38:35.487 回答
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
于 2013-10-24T16:59:12.957 回答
0

在您的 for 循环中,当您将 %%i 的值分配给 finame 时,您将替换以前的值,因此只有最后一个文件会回显到控制台。

如果您尝试使用 findstr 命令(在 for 之外),您将看到文件列表。

于 2013-10-24T14:44:27.000 回答