如何替换Windows批处理文件中的变量内容

GKe*_*lly 12 windows cmd batch-file

我正在编写一个简单的脚本来替换环境变量中的文本和其他文本.我遇到的麻烦是从其他变量中提取替换或替换文本

SET a=The fat cat
ECHO %a%
REM Results in 'The fat cat'
ECHO %a:fat=thin%
REM Results in 'The thin cat'
Run Code Online (Sandbox Code Playgroud)

工作正常(输出是'肥猫'和'瘦猫'

但是,如果'fat'或'thin'在变量中,它就不起作用

SET b=fat
ECHO %a:%c%=thin%
REM _Should_ give 'The thin cat'.
REM _Actually_ gives '%a:fat=thin%' (the %c% is evaluated, but no further).

REM using delayed evaluation doesn't make any difference either
ECHO !a:%c%=thin!
REM Actual output is now '!a:fat=thin!'
Run Code Online (Sandbox Code Playgroud)

我知道这可以像以前在博客中看到的那样完成,但我从未保存过博客的链接.

有人有主意吗?

PS.我在Windows 7上运行脚本

PPS.我知道这在Perl/Python /其他脚本语言中更容易选择,但我只是想知道为什么那些应该很容易的事情并不是很明显.

购买力平价.我还尝试了明确打开延迟扩展的脚本

SETLOCAL enabledelayedexpansion
Run Code Online (Sandbox Code Playgroud)

这没什么区别.

Pau*_*asi 13

请尝试以下方法:

将代码复制并粘贴到记事本中,并将其另存为批处理文件.

   @echo off
   setlocal enabledelayedexpansion

   set str=The fat cat
   set f=fat

   echo.
   echo          f = [%f%]

   echo.
   echo        str = [%str%]

   set str=!str:%f%=thin!

   echo str:f=thin = [%str%]
Run Code Online (Sandbox Code Playgroud)

我希望你确信!


Cor*_*uzu 9

使用CALL.将以下内容放在批处理脚本中并运行它:

set a=The fat cat
set b=fat
set c=thin

REM To replace "%b%" with "%c%" in "%a%", we can do:
call set a=%%a:%b%^=%c%%%
echo %a%
pause
Run Code Online (Sandbox Code Playgroud)

如前所述这里,我们使用的事实是:

CALL internal_cmd

...

internal_cmd运行内部命令,首先展开参数中的所有变量.

在我们的例子中,internal_cmd最初设置为a = %% a:%b%^ =%c %%%.

后膨胀internal_cmd变为设定=%A:脂肪=%薄.

因此,在我们的情况下运行

call set a = %% a:%b%^ =%c %%%

等同于运行:

设a =%a:脂肪=瘦%.