Batch file to sum numbers from text files and writ

2019-06-06 07:59发布

i have 300 text files in folder1 and 300 text files in folder2

below is a sample content of one text file

india,car,10
uk,car,20
us,car,50

i want to sum the 3rd column and write that total to same text file. example,

for /f "tokens=3 delims=," %%a in (folder1\textfile1.txt) do set /a total+=%%a
echo %total% >folder1\textfile1.txt 

the above code will write 80 in textfile1.txt

please tell how to do the same for all the 300 text files using a batch file.

1条回答
Melony?
2楼-- · 2019-06-06 08:39
@echo off
for %%F in (
  folder1\*.txt
  folder2\*.txt
) do (
  set /a total=0
  for /f "usebackq tokens=3 delims=," %%a in ("%%F") do set /a total+=%%a
  echo %total% >"%%F"
)

Important points:

1) You are replacing the content of each file (many lines) with a single line containing the total. If you want to preserve the original data and append the total to the end then you need to use >> instead:

echo %total% >>"%%F"

2) The maximum integer value that batch can compute is 2,147,483,647. The sum total must be less than or equal to that number for each file, else it will fail. If it is possible that your total can exceed that value then you will have to use some other language. Perhaps JScript, VBScript, or PowerShell.

查看更多
登录 后发表回答