-
如果行包含关键字word1,则在文件中查找VALUE1并显示VALUE1。
-
如果行包含关键字word1,请在文件中查找值2。
-
-
-
示例文件(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