Replacing Characters in String
53,407
Solution 1
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%!
Solution 2
Try this
setlocal
set string=cat rat mat fat
set string=%string:t=p%
Related videos on Youtube
Author by
LabRat
Updated on July 16, 2022Comments
-
LabRat almost 2 years
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
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%
-
Claudio about 7 yearsJust the 2 cents for the for loop: - Look for instruction about using ! instead of % for variables.
-
-
LabRat over 11 yearsSays that the batch operation is not recognised?
-
LabRat over 11 yearsThis now has a message box saying T=P which is not what I was after?
-
LabRat over 11 yearsI see what whent wrong your reply says TEXt not MY-TEXT works now :)
-
Grhm over 11 years
sed
is not recognised on windows unless you go out of your way to get it installed. -
Admin over 11 yearsohh sorry my bad. If you have ruby you could invoke
ruby -e 'puts ARGV[0].gsub("t","p")' "cat rat mat fat"
-
Lizz over 9 yearsI found this technique very helpful, but found it doesn't work inside a
FOR
loop. -
Grhm over 9 years@Lizz: Variable expansion in a
FOR
loop can be tricky. The variables normally are expanded before theFOR
loop begins, you can fix some issues by enabling delayed expansion, see robvanderwoude.com/variableexpansion.php for more details and worked examples. However, this technique is using delayed expansion already, so I'm not sure what you'd need to do to get it to work in aFOR
loop. I suspect it depends on what theFOR
loop is doing and how it does it. -
Lizz over 9 yearsYeah, I used Rob's page but it didn't address this. I was lucky and could move your solution out of the
FOR
loop this time, but have no clue how it could be done inside aFOR
loop. Tried a simple one and it broke. :(