我有一個代碼可以使用以下代碼從多個檔案中列印所有字串:
for /f %%A in ('findstr /R "[0-9]" *.txt') do echo %%A
然而,當切換到不同的檔案時輸出連接:
C:\Users>echoarray.cmd
File1.txt:123
File1.txt:321
File1.txt:312File2.txt:456
File2.txt:654
File2.txt:546File3.txt:789
File3.txt:678
File3.txt:777File4.txt:123
File4.txt:789
File4.txt:999
我想要做的是,將每行所有整數的總和(來自 *.txt)放入陣列中,然后將輸出列印到一個文本檔案中:
(感謝 Gerhard從這里找到了這個)
@echo off & setlocal enabledelayedexpansion
for /f "tokens=1* delims=:" %%a in ('findstr /R "[0-9]" *.txt') do (
set /a %%a =1
set /a result[!%%a!] =%%b
echo result[!%%a!] > result.txt
)
示例結果如下(來自上面 echoarray.cmd 的輸出):
1491 ::my comment: first row result are from summation of 123 456 789 123
*continue for second row
*continue for third row
*continue for fourth row
我需要您的幫助來解決 findstr 的連接輸出(希望有人也可以建議我為陣列提供正確的解決方案)。
P/S:我在 Windows 10 上使用 cmd
uj5u.com熱心網友回復:
也許這樣的事情會滿足您的需求。
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F "Delims==" %%G In ('"(Set Line[) 2>NUL"') Do Set "%%G="
Set "}=" & For /F "Tokens=1,* Delims=[]" %%G In ('
%SystemRoot%\System32\find.exe /N /V "" "*.txt" 2^>NUL ^|
%SystemRoot%\System32\findstr.exe /R "^\[[123456789][0123456789]*\][123456789][0123456789]*$"'
) Do Set /A Line[%%G] = %%H, } = %%G
If Not Defined } GoTo :EOF
(For /F "Tokens=1,* Delims==" %%G In ('"(Set Line[) 2>NUL"') Do Echo %%H) 1>"result.txt"
上面的代碼用于find.exe獲取每個.txt檔案的內容,而不會因缺少CRLF行尾而絆倒。然后findstr.exe只識別那些只包含一系列數字的行,并將這些行傳遞給Do回圈之外的部分。Set /A然后以行號為基礎對內容進行總計,并.txt僅將這些結果列印到檔案中。
請注意,由于這使用Set /A并因此忽略了第一個數字是 a 的任何行0。這可以防止八進制算術可能出現的問題。您還應該注意,由于您請求的輸出字串,如果您的任何檔案包含一些包含非數字字符的行,您將無法確定哪些總數屬于哪些行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/388368.html
上一篇:如何撰寫類似不和諧游戲活動的程式
