2013-10-24 67 views
1

我刚刚开始用MS批处理文件弄湿我的脚。我创建了一个小批量,它使用findstr/m在所输入的目录中搜索包含特定字符串的文件。它返回一个包含该字符串的文件,但只返回它找到的第一个文件。我搜查了findstr /?和在线命令参考,以及本网站。我无法找到findtr用字符串实例返回所有文件的方法。我错过了什么?findstr/m只返回找到的第一个文件名

@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

如果有人问,我加了暂停,这样我就可以确定我的ELSE语法是正确的。它可以被删除。 – Develmann

回答

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 
+0

谢谢,我刚刚弄明白了!我会问是否有一种方法可以将所有输出放置在一个变量中,但我认为如果您有很多返回的文件名,这会变得很难看。 – Develmann

0

在你的for循环中,当分配给finame%的值%i,你正在替换之前的值,所以只有最后一个文件被回显到控制台。

如果您尝试您的findstr命令(出于for),您将看到文件列表。

0

将所有的变种:

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 
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 
相关问题