Search code examples
stringbatch-filebatch-processingiperf

batch - delete last char from string


I've got the following string out of a jSON-File:

39468856,

Now, I want to calculate with this numbers.. because of that, I've to remove the , at the end.

At this moment I use the following code:

for /f "skip=24 tokens=2" %%a in (text.txt) do ( 

Set %%a=%%a:~0,1%
echo %%a

SET /a b=a*2
echo %%a
@echo Uebertragen in 10s:

echo %%a bytes

)

The Set %%a=%%a:~0,1% isn't working for me.. and neither the SET /a b=a*2 (maybe because of the , in it).

Please help me with this...

Thanks in advance


Solution

  • Without seeing the full code and the input file, these could be some of the simplest solutions.

    for /f "skip=24 tokens=2" %%a in (text.txt) do for %%b in (%%a) do set /a "b=%%b*2"
    echo %b%
    

    This option removes the comma, that is handled as a delimiter, using a second for loop.

    for /f "skip=24 tokens=2" %%a in (text.txt) do 2>nul set /a "b=2*%%a"
    echo %b%
    

    In this case, the order of the operands has been changed and the error output (the comma is still there) discarded.

    If the input file data allows it, maybe this could be used

    for /f "skip=24 tokens=2 delims=, " %%a in (text.txt) do set /a "b=%%b*2"
    echo %b%
    

    including the comma as a delimiter in the for /f, the tokenizer will discard it and the comma will not be included in the retrieved data.

    In all cases, as the echo has been moved out of the block of code that sets the variable there is no need for delayed expansion.

    But, maybe, none of this options can be used. Then your best option is to use delayed expansion

    setlocal enabledelayedexpansion
    for /f "skip=24 tokens=2" %%a in (text.txt) do ( 
        for %%b in (%%a) do set /a "b=%%b*2"
        echo !b!
    )
    

    Or, with the original substring approach

    setlocal enabledelayedexpansion
    for /f "skip=24 tokens=2" %%a in (text.txt) do ( 
        set "b=%%a"
    
        rem Any of these could work
        set "b=!b:~0,-1!"
        set "b=!b:,=!"
    
        set /a "b*=2"
        echo !b!
    )