string 替换字符串中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13469939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:43:17  来源:igfitidea点击:

Replacing Characters in String

stringwindowsbatch-filecharacter

提问by ABANDOND ACOUNT

I am trying to replace all instances of a character in a string of text with another character but I'm not succeeding.

我试图用另一个字符替换文本字符串中一个字符的所有实例,但我没有成功。

Suppose the text is

假设文本是

cat rat mat fat

I want the script to replace all the t's to p's

我希望脚本替换所有 t's to p's

cap rap map fap

What I have is the following but it seems to do little for me.

我所拥有的是以下内容,但它似乎对我没什么用。

SET /P MY_TEXT=ENTER TEXT:

SET T2P=P

SET NEW_TEXT=%TEXT=:T!T2P!%

MSG * %NEW_TEXT%

采纳答案by Grhm

You've got the =sign in the wrong place. Try:

=在错误的地方找到了标志。尝试:

setlocal enabledelayedexpansion
set /P MY_TEXT=ENTER TEXT:
SET T2P=P
set NEW_TEXT=%MY_TEXT:T=!T2P!%
MSG * %NEW_TEXT%

You can also do the expansion the other way round, i.e.

您也可以反过来进行扩展,即

set NEW_TEXT=!MY_TEXT:T=%T2P%!

回答by Justin

Try this

尝试这个

setlocal 
set string=cat rat mat fat
set string=%string:t=p%

回答by Grhm

You could use 'sed' like this:

你可以像这样使用“sed”:

echo "cat rat mat fat" | sed 's/t/p/g'  # outputs "cap rap map fap"