在文本文件中添加具有相同ID的值

时间:2017-12-08 11:14:34

标签: windows file file-manipulation

我想知道是否有一个Windows命令可以在文件中添加两个具有相同ID的不同值。

例如:

档案:

id;value
01;25
02;12
01;2
03;21
03;-5

结果:

id;value
01;27 /* 25 + 2 */
02;12
03;16 /* 21 - 5 */

1 个答案:

答案 0 :(得分:0)

对于那些需要答案的人,我找到了一种方法:

setlocal EnableDelayedExpansion
echo off

rem write header in output file
echo id;value> output.csv

rem remove the header of the file and loop
for /f "tokens=1,2 delims=;" %%A in ('more +1 my_file.csv') do (
    set "result="

    rem search if current id is in the temp list (tmp file) of processed ids
    for /f "delims=" %%i in ('findstr /c:"%%A;" output.csv') do set result=!result!%%i

    rem if the id is not in tmp file (the id is not yet processed)
    if "!result!"=="" (
        set sum=0
        rem get all values related to the current id and calculate the sum 
        for /f "tokens=2 delims=;" %%V in ('findstr /c:"%%A;" my_file.csv') do (
            set /a sum+=%%V
        )
        echo %%A;!sum!>> output.csv
    )
)