使用变量替换批处理文件子串

时间:2012-08-09 22:29:10

标签: variables batch-file substring replace

在使用变量时,我无法让此批处理文件进行子字符串替换。特别当!原创!指定变量;如果它是一个文字字符串,它工作正常。但是,这不适合我的使用。

setlocal ENABLEDELAYEDEXPANSION
set original=chair
set replacement=table
set str="jump over the chair"
set str=%str:!original!=!replacement!%

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:14)

如果您使用call,则可以在不需要setlocal enabledelayedexpansion的情况下执行此操作,如下所示:

call set str=%%str:%original%=%replacement%%%

注意:首先将其解析为call set str=%str:chair=table%

答案 1 :(得分:3)

您的扩展订单已被撤销。

正常(百分比)扩展发生在分析时(第1)
延迟(感叹号)扩展在运行时(第二次)发生

在搜索和替换之前,必须扩展搜索和替换术语。所以你想要:

set str=!str:%original%=%replacement%!