批处理:组合字符串操作

batch: combine string operations

我想结合以下字符串操作...

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

...像这样:

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

编辑

让您了解我打算做什么:

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

..这应该是没有任何辅助变量的单个 SET 命令。

你的意思是这样?

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

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

但遗憾的是,根据您在我发布后发表的评论。批量替换多个没有单行替换

您可以使用 wmic 获得更可靠的值,唯一的区别是,在没有进一步的字符串操作的情况下,给出了完整的年份 (YYYY):

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

我不认为有在一个命令中组合多个字符串操作的解决方案,但您可以使用 for /f 执行类似的操作。

起初与上面相同的结果(YYYY 格式):

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

这里是您在问题中使用的格式:

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 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