batch: combine string operations

86 Views Asked by At

I'd like to combine the following string operations...

SET MYVAR=someStringWithSomeExpressionInside
SET MYVAR=%MYVAR:Expression=thing%
SET MYVAR=%MYVAR:~4%

...to something like this:

SET MYVAR=%MYVAR:Expression=thing~4%

EDIT

To give you an idea of what i'm intend to do:

SET TIMESTAMP=%DATE:~8,2%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
SET TIMESTAMP=%TIMESTAMP: =0%

..this should be a single SET command without any helper variables.

2

There are 2 best solutions below

1
Gerhard On BEST ANSWER

You mean like this?

set "MYVAR=someStringWithSomeExpressionInside"
set "MYVAR1=%MYVAR:Expression=thing%"
set "MYVAR2=%MYVAR1:~4%"
set "VAR=%MYVAR%%MYVAR1%%MYVAR2%"
echo %VAR%

or

set "MYVAR=someStringWithSomeExpressionInside"
set "VAR=%MYVAR%%MYVAR:Expression=thing%%MYVAR:~4%"
echo %VAR%

but sadly, as per you comment after I posted this. There is no single line replacement for multiple replace in batch.

0
timlg07 On

You can get the value more reliable with wmic, only difference is that, without further string manipulation, the full year (YYYY) is given:

for /F "tokens=2 delims==." %%t in ('wmic OS Get localdatetime /value') do set stamp=%%t

I don't think there is a solution to combine multiple string operations in one command, but you can do something similar with for /f.

At first with the same result as above (YYYY-format):

for /F "tokens=1-6 delims=,.:" %%a in ("%date%,%time%") do set stamp=%%c%%b%%a%%d%%e%%f

And here in the format you used in the question:

for /F "tokens=1-6 delims=,.:" %%a in ("%date:~0,6%%date:~8,2%,%time%") do set stamp=%%c%%b%%a%%d%%e%%f

Here are all versions combined, creating equal output:

@echo off

SET TIMESTAMP=%DATE:~8,2%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
SET TIMESTAMP=%TIMESTAMP: =0%
echo #1=%TIMESTAMP%

for /F "tokens=2 delims==." %%t in ('wmic OS Get localdatetime /value') do set stamp=%%t
echo #2=%stamp:~2%

for /F "tokens=1-6 delims=,.:" %%a in ("%date%,%time%") do set stamp=%%c%%b%%a%%d%%e%%f
echo #3=%stamp:~2%

for /F "tokens=1-6 delims=,.:" %%a in ("%date:~0,6%%date:~8,2%,%time%") do set stamp=%%c%%b%%a%%d%%e%%f
echo #4=%stamp%

pause