Search code examples
windowsbatch-filecmdcommand-prompt

How to manipulate a variable multiple times in a single command in CMD?


Everyone. I was wondering if it was possible to manipulate a variable multiple times in a single command?

For example, I want to SUBSTRING and REPLACE TEXT as the following commands:

:: Print the first 8 characters:
echo %TIME:~0:8%

:: Replace white spaces with zeros
echo %TIME: =0%

Desired output (Print Time without the milliseconds AND replace the whitespace on the left side with a 0)

09:15:23

So, is there away I could combine both variable manipulations into one single command?

I want to avoid storing the time in an additional variable and just print it out the way I desire (as mentioned above).


Solution

  • Each variable manipulation manipulates one variable, so your result requires two commands. You can, however, place the two commands in a single line and re-use the same variable in order to not initialize an additional variable. That is:

    @echo off
    setlocal EnableDelayedExpansion
    
    set "TIME=%TIME: =0%" & echo !TIME:~0,8! & set "TIME="