我正在处理一个脚本,该脚本从一个txt行中的文件中收集值,我通过使用findstr引用一个关键字来找到这些值。我想要完成的过程是:
示例文件(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
答案 0 :(得分:1)
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q44875889.txt"
SET "word1=%~1"
SET "word2=%~2"
FOR /f "tokens=4,8,9,10,11delims= " %%a IN ('findstr /Li /c:"%word1%" /c:"%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
您需要更改sourcedir
的设置以适合您的具体情况。
我使用了一个名为q44875889.txt
的文件,其中包含我的测试数据。
为我们提供真实的数据要好得多。
处理应该是显而易见的 - 读取findstr
的每一行输出,它正在寻找任何一个单词并选择适当的标记。
如果第一个单词出现在所需位置,请对其进行处理并保存所需的value2
。 Ditto第二个单词,计算总数并使用delayed expansion
显示total
的运行时值
尝试处理不是所需格式的行没有明显的意义。
重要(但最初省略)运行说明:
以
运行thisbatchname 苹果桃子
然后在我的原始帖子中将提供的两个单词替换为word1 /。