我正在處理一個腳本,該腳本從位於一行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「 '。非常感謝您處理循環的輸入! –