Home > Enterprise >  Batch script calculate integer (add) from each row from multiple text files
Batch script calculate integer (add) from each row from multiple text files

Time:12-17

I have multiple text files contains integer on each row. Can loop for /f calculate (add) from each row sequentially?

Lets say the text files are like this:

File1.txt
123
213
321

File2.txt
111
222
333

File3.txt
333
222
111

Is it possible to calculate and print the calculation like this:

set /A calc=%%A %%a %%x    :: %%A, %%a, %%x are from nested loop probably,
                           :: operation for 1st row should be like calc=123 111 333 
echo !calc!

After googling around, I could not find any solution similar to my problem.

Appreciate if anyone can provide insight on this.

Thanks

CodePudding user response:

you can use a single for loop over the output of findstr to build counts from each lines value.

@Echo off & CD /D "%~dp0"
cls

Setlocal

 For /f "tokens=1 Delims==" %%g in ('set Line[ 2^> nul')Do Set "%%g=" 2> nul

 For /f "tokens=2,3 delims=:" %%i in ('%Systemroot%\System32\Findstr.exe /n /r "^[0123456789]*$" "file*.txt"')Do (
  Set /A "Line[%%i] =%%j 0" 2> nul
 )

 Set Line[
Endlocal

CodePudding user response:

You can use an array this way:

@echo off
setlocal EnableDelayedExpansion

for %%f in (file*.txt) do (
   set "i=1"
   for /F %%n in (%%f) do set /A "calc[!i!] =%%n, i =1"
)

set /A i-=1
for /L %%i in (1,1,%i%) do echo calc[%%i] = !calc[%%i]!
  • Related