简体   繁体   English

替换字符串中的字符

[英]Replacing Characters in String

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替换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%

Try this 试试这个

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

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, ie 您也可以反过来进行扩展,即

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

您可以像这样使用'sed':

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM