![](/img/trans.png)
[英]How to write a batch script to loop through logfiles in directory and generate a “filename.found” if i find the string “found” in the log file?
[英]Batch Script to find string in directory and all subdirectories
我想编写一个批处理文件,它使用 find 命令在父目录和所有子目录中查找字符串,并将该输出打印到文本文件,然后在完成后打开文本文件。 到目前为止,我的代码如下所示:
@echo off
set /p "var1= Enter the String to Find: "
for /F "delims=" %a in ('dir /B /S *.txt') do @(find /i "%var1" "%a" 1>nul 2>&1 && find /i "%var1" "%a") >> result.txt
start result.txt
但这目前甚至没有向 result.txt 写入任何内容,尽管我确信我搜索的字符串出现在多个 .txt 文件中。 我知道它必须是语法方面的,但我似乎无法弄清楚。
您的脚本中有一些错误:
set
命令的等号后不应有空格。 具体来说,删除set /p "var1=
之后的空格。
要展开的变量,你必须把百分号之前和变量名后,因此,与其%var
使用%var%
与您的问题没有直接关系,但是您为什么要两次调用find
?
我还使用了一个临时文件,因此find
不会搜索result.txt
。
请注意,如果您从文件运行批处理脚本,则在使用循环变量时需要使用双百分号,例如: %%a
无论如何,这是固定的脚本,希望能做你想做的事:
@echo off
set RESULT_FILE="result.txt"
set /p "var1=Enter the String to Find: "
pushd %~p0
type NUL > %RESULT_FILE%.tmp
for /f "delims=" %%a in ('dir /B /S *.txt') do (
for /f "tokens=3 delims=:" %%c in ('find /i /c "%var1%" "%%a"') do (
for /f "tokens=*" %%f in ('find /i "%var1%" "%%a"') do if %%c neq 0 echo %%f
)
) >> "%RESULT_FILE%".tmp
move %RESULT_FILE%.tmp %RESULT_FILE% >nul 2>&1
:: Open the file
"%RESULT_FILE%"
popd
只是 findstr abc *
相反, findstr /v 将打印所有没有 abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.