Home > Enterprise >  Add numbers with same text together
Add numbers with same text together

Time:06-19

I would like to create a batch file in which I can see what I have collected in a game. The game saves this information in a .txt file. The output would look like this.

70x Silver.
Back Pearl.
41x Copper.
Amethyst.
Amethyst.
12x Silver.
Back Pearl.
21x Copper.
5x Silver.
Back Pearl.
Back Pearl.
Amethyst.

What I want to do now, is to add the items with the same name together, like this:

128x Silver.
4x Back Pearl.
62x Copper.
3x Amethyst.

There are hundreds of items with different names, not just these 4. Would that be possible? Any help would be appreciated. Thanks!

CodePudding user response:

Would that be possible? - Yes.

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in (t.txt) do (
  set " z=%%a"
  set " z=!z:x =@!"
  set " z=!z: =_!"
  for /f "tokens=1,2 delims=@" %%b in ("!z!") do (
    if "%%c" == "" (
      set "x=1"
      set "y=%%b
    ) else (
      set "x=%%b"
      set "y=%%c"
    )
    set /a #!y! =!x!
  )
)
(for /f "tokens=1,2 delims=#=" %%a in ('set #') do (
  set "x=%%a"
  echo %%bx !x:_= !
))>summary.txt
type summary.txt

Output with your example data (I hope, alphabetic sorting is ok for you):

3x Amethyst.
4x Back Pearl.
62x Copper.
87x Silver.

(your calculation of 120 silver might be a bit optimistic with the given input data)

CodePudding user response:

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q72672485.txt"

:: remove variables starting #
FOR  /F "delims==" %%b In ('set # 2^>Nul') DO SET "%%b="

FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 CALL :sub %%b
)
SETLOCAL ENABLEDELAYEDEXPANSION 
FOR  /F "tokens=1,2delims==" %%b In ('set # 2^>Nul') DO (
 SET "line=%%cx%%b"
 ECHO !line:#= !
)>summary.txt
endlocal
type summary.txt
GOTO :EOF

:sub
SET "quantity=%1"
SET "line=%*"
IF /i "%quantity:~-1%"=="x" (SET /a quantity=%quantity:~0,-1%&SET "line=%line:* =%") ELSE SET quantity=1
IF %quantity%==0 SET /a quantity=1&SET "line=%*"
SET /a #%line: =#% =quantity
GOTO :eof

Different approach...

CodePudding user response:

Another one!

@echo off
setlocal EnableDelayedExpansion

for /F "delims=" %%l in (test.txt) do for /F "tokens=1*" %%a in ("%%l") do (
   set "first=%%a"
   if "!first:~-1!" equ "x" (set /A "num=!first:~0,-1!") else set "num=0"
   if !num! equ 0 (
      set "rest=%%l"
      set /A "count[!rest: =_!] =1"
   ) else (
      set "rest=%%b"
      set /A "count[!rest: =_!] =num"
   )
)

(for /F "tokens=2* delims=[]=" %%a in ('set count[') do (
   set "item=%%a"
   if %%b equ 1 (
      echo !item:_= !
   ) else (
      echo %%bx !item:_= !
   )
)) > summary.txt
  • Related