Home > Blockchain >  For Loop in (Findstr *.txt) Output Concatenated Between Files
For Loop in (Findstr *.txt) Output Concatenated Between Files

Time:12-21

I have a code to print all string from multi files with below code:

for /f %%A in ('findstr /R "[0-9]" *.txt') do echo %%A

However the output concatenated when switching to different files:

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

What I want to do is, to put sum of all integer per row (from *.txt) into array then print output into one text file:

(Found this from here thanks to 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
)

Example results would be like below (from output of echoarray.cmd above):

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

I need your kind help to solve the concatenated output from findstr (hopefully someone can suggest me the correct solution for the array too).

P/S: I am using cmd on Windows 10

CodePudding user response:

Perhaps something like this will satisfy your needs.

@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"

The above code uses find.exe to get the content of each .txt file, without tripping up on the lack of CRLF line endings. Then findstr.exe identifies only those lines which contain only a series of digits and passes those to the Do portion off the loop. Set /A then totals the content on a line number basis and prints to a .txt file only those results.

Please be aware that as this uses Set /A and has therefore ignored any lines where the first digit is a 0. This prevents possible issues with octal arithmetic. You should also be aware that due to your requested output strings, there is no way of you determining which totals belong to which lines, if any of your files contain some lines with non digit only characters in them.

  • Related