我正在处理一个脚本,该脚本从位于一行txt中的文件收集值,并通过使用findstr和引用关键字来查找这些值。我想要完成的过程如下:Findstr结果操作&循环批处理文件
- 如果该行包含关键字“word1”并显示VALUE1,则在该文件中查找VALUE1。
- 如果该行包含关键字“word1”,则在文件中查找VALUE2。
- 如果该行包含关键词“word2”(我也知道该值将在单独的行中),请在文件中查找VALUE3。
- 添加VALUE2和VALUE3并将此值显示为TOTAL。
- 再次循环遍历文件并使用步骤1-4,如果存在另一组VALUE1,VALUE2和VALUE3,则显示另一个TOTAL。
实施例文件(的test.txt):
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
Hello today is 05032017 and you have 5 apples
Also it is good to know that you bought 6 peaches
关键词:“苹果”,“桃子”
希望的输出:
First value is: 05022017
Second value is: 4
Third value is: 5
TOTAL: 9
First value is: 05032017
Second value is: 5
Third value is: 6
TOTAL: 11
当前代码:
@echo off
FOR /f "tokens=4,8" %%a in ('type test.txt ^|findstr /i "apples"') do (
echo(First value is: %%a
echo(Second value is: %%b
)
FOR /f "tokens=10" %%c in ('type test.txt ^|findstr /i "peaches"') do (
echo(Value on another line is: %%c
)
echo(All done!
echo(&pause&goto:eof
电流输出:
First value is: 05022017
Second value is: 4
First value is: 05032017
Second value is: 5
Value on another line is: 5
Value on another line is: 6
我明白为什么我的代码工作它的方式。我知道我有两个独立的循环,我首先找到第一个和第二个值,然后找到分开的第三个值。我试图使用向量,嵌套循环,并赋值给变量,但我似乎无法得到我想要的工作。
我希望能够在有N可能性的文件运行此脚本,这意味着它应该与这两个文件的情况下工作:
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
或者
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
Hello today is 05022017 and you have 4 apples
Also it is good to know that you bought 5 peaches
我将不胜感激任何帮助我可以得到一些指导,或者我可以如何以不同的方式解决这些问题
谢谢!
更新工作代码:
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=I:\Tests"
SET "filename1=%sourcedir%\test.txt"
SET "word1=apples"
SET "word2=peaches"
FOR /f "tokens=4,8,9,10,11 delims= " %%a IN ('findstr "%word1% %word2%" "%filename1%"') DO (
IF /i "%%~c"=="%word1%" (
REM apple line
ECHO First value is: %%a
ECHO Second value is: %%b
SET /a value2=%%b
)
IF /i "%%~e"=="%word2%" (
REM peaches line
ECHO Third value is: %%d
SET /a total=value2 + %%d
ECHO Total: !total!
)
)
GOTO :EOF
谢谢你的响应!对不起,我的结局有所延误。执行批处理文件时,出现“FINDSTR:参数缺失/ c后”的错误。我现在正在浏览它,但如果你明白为什么马上请让我知道。 –
在'/ c'之后缺少冒号 - 从这里不难看出。需要您通过剪切粘贴来发布您正在使用的*实际*代码。剪切和粘贴也是复制在SO上发布的代码的最佳方式 - 它不仅更快,更容易,而且避免了转录错误。 – Magoo
我知道它能正常工作。我开始工作的findstr格式看起来像这样('findstr“%word1%%word2%”“%filename1%”')',我实际上设置了像SET这样的词word1 = apples“SET”word2 = peaches“ '。非常感谢您处理循环的输入! –