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%
Share:
53,407

Related videos on Youtube

LabRat
Author by

LabRat

Updated on July 16, 2022

Comments

  • LabRat
    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
      Claudio about 7 years
      Just the 2 cents for the for loop: - Look for instruction about using ! instead of % for variables.
  • LabRat
    LabRat over 11 years
    Says that the batch operation is not recognised?
  • LabRat
    LabRat over 11 years
    This now has a message box saying T=P which is not what I was after?
  • LabRat
    LabRat over 11 years
    I see what whent wrong your reply says TEXt not MY-TEXT works now :)
  • Grhm
    Grhm over 11 years
    sed is not recognised on windows unless you go out of your way to get it installed.
  • Admin
    Admin over 11 years
    ohh sorry my bad. If you have ruby you could invoke ruby -e 'puts ARGV[0].gsub("t","p")' "cat rat mat fat"
  • Lizz
    Lizz over 9 years
    I found this technique very helpful, but found it doesn't work inside a FOR loop.
  • Grhm
    Grhm over 9 years
    @Lizz: Variable expansion in a FOR loop can be tricky. The variables normally are expanded before the FOR 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 a FOR loop. I suspect it depends on what the FOR loop is doing and how it does it.
  • Lizz
    Lizz over 9 years
    Yeah, 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 a FOR loop. Tried a simple one and it broke. :(