该程序搜索包含特定关键字的文件,其任务的一部分是显示正在搜索的关键字。关键字在它读取的文本文件中一个接一个地写在上面。但是,它只从最后一行读取?可能是一个非常简单的错误,但我错过了它......
@echo off
:main_section
set main_dir=%cd%
set key1=variable
set key2=variable
set key3=variable
set key4=variable
set key5=variable
for /f "delims=" %%a in (keylist.txt) do set "key1=%%a"
for /f "skip=1 delims=" %%b in (keylist.txt) do set "key2=%%b"
for /f "skip=2 delims=" %%c in (keylist.txt) do set "key3=%%c"
for /f "skip=3 delims=" %%d in (keylist.txt) do set "key4=%%d"
for /f "skip=4 delims=" %%e in (keylist.txt) do set "key5=%%e"
echo warning: do not launch from the userprofile directory
echo warning: write exactly five keywords in keylist.txt
echo searching for %key1%, %key2%, %key3%, %key4%, %key5%
pushd collection
>>%key1%.txt findstr /i /p /s %key1% %userprofile%\*.* >nul
echo search for %key1% complete - printed to collection\%key1%.txt
>>%key2%.txt findstr /i /p /s %key2% %userprofile%\*.* >nul
echo search for %key2% complete - printed to collection\%key2%.txt
>>%key3%.txt findstr /i /p /s %key3% %userprofile%\*.* >nul
echo search for %key3% complete - printed to collection\%key3%.txt
>>%key4%.txt findstr /i /p /s %key4% %userprofile%\*.* >nul
echo search for %key4% complete - printed to collection\%key4%.txt
>>%key5%.txt findstr /i /p /s %key5% %userprofile%\*.* >nul
echo search for %key5% complete - printed to collection\%key5%.txt
pushd %main_dir%
for /f "tokens=3" %%f in ('dir "collection"^|find "File(s)"') do set size=%%f
set "size=%size:,=%"
echo %size% bytes of information collected
echo press any key to exit the program
pause >nul
答案1
可能是一个非常简单的错误,但我却忽略了它......
您的for
循环正在处理文件中的所有行,因此只存储文件中的最后一个值。
您可以简化批处理文件并使用单个for
循环和延迟扩张和一个柜台。
这是一个小的批处理文件,可为您提供基本解决方案。将其与您的批处理文件结合使用。
测试.cmd:
@echo off
setlocal enabledelayedexpansion
set /a _index=1
for /f "delims=" %%a in (keylist.txt) do (
set "key!_index!=%%a"
set /a _index+=1
)
echo searching for !key1!, !key2!, !key3!, !key4!, !key5!
endlocal
示例输出:
> type keylist.txt
1
2
3
4
5
> test
searching for 1, 2, 3, 4, 5
进一步阅读
- Windows CMD 命令行的 AZ 索引- 与 Windows cmd 行相关的所有事物的绝佳参考。
- 启用延迟扩展- 延迟扩展将导致变量在执行时而不是在解析时扩展。
- 为了- 有条件地执行命令多次。
- 放- 显示、设置或删除 CMD 环境变量。使用 SET 所做的更改将仅在当前 CMD 会话期间保留。