如何替换变量内容在Windows批处理文件 [英] How to substitute variable contents in a Windows batch file
问题描述
我在写一个简单的脚本与其他文本的环境变量来代替文字。我得到麻烦的是与取代或取代文本和其他变量被拉
I'm writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables
SET a=The fat cat
ECHO %a%
REM Results in 'The fat cat'
ECHO %a:fat=thin%
REM Results in 'The thin cat'
工作正常(输出是'肥猫'和'瘦猫
Works fine (output is 'The fat cat' and 'The thin cat'
然而,如果'脂肪或薄是变量,它不工作
However, if 'fat' or 'thin' are in variables, it doesn't work
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!'
我知道这可能是我在博客看到它之前完成,但我从来没有保存的链接的博客。
I know this can be done as I've seen it in blogs before, but I never saved the link to the blogs.
任何人有什么想法?
PS。我在Windows 7
PS. I'm running the scripts on Windows 7
PPS。我知道这是在Perl / Python的/其他脚本所选择的语言更容易,但我只是想知道为什么事情应该很容易是不是很明显。
PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.
购买力平价。我也试图与延迟扩展明确打开了脚本
PPPS. I've also tried the scripts with delayed expansion explicitly turned on
SETLOCAL enabledelayedexpansion
这没什么区别。
推荐答案
请尝试以下操作:
复制和code粘贴到记事本,并保存为一个批处理文件。
Copy and paste the code into Notepad and save it as a batch file.
@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%]
我希望你相信!
这篇关于如何替换变量内容在Windows批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!