String replacement in batch file

2020-01-27 01:22发布

We can replace strings in a batch file using the following command

set str="jump over the chair"
set str=%str:chair=table%

These lines work fine and change the string "jump over the chair" to "jump over the table". Now I want to replace the word "chair" in the string with some variable and I don't know how to do it.

set word=table
set str="jump over the chair"
??

Any ideas?

3条回答
老娘就宠你
2楼-- · 2020-01-27 01:29

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

查看更多
forever°为你锁心
3楼-- · 2020-01-27 01:39

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%
查看更多
霸刀☆藐视天下
4楼-- · 2020-01-27 01:43

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%
查看更多
登录 后发表回答