I'm having trouble getting this batch file to do substring replacements when variables are used. Specifically when the !original! variable is specified; if it's a literal string it works fine. However, this will not do for my usage.
setlocal ENABLEDELAYEDEXPANSION
set original=chair
set replacement=table
set str="jump over the chair"
set str=%str:!original!=!replacement!%
Your help is greatly appreciated.
So %%k refers to the value of the 3rd token, which is what is returned.
%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used.
Use the syntax below to edit and replace the characters assigned to a string variable. Syntax %variable:StrToFind=NewStr% %~[param_ext]$variable:Param Key StrToFind : The characters we are looking for (not case sensitive). NewStr : The chars to replace with (if any).
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
If you use call
you can do this without the need for setlocal enabledelayedexpansion
, like so:
call set str=%%str:%original%=%replacement%%%
Note: This first gets parsed to call set str=%str:chair=table%
You have got your expansion order reversed.
Normal (percent) expansion occurs at parse time (1st)
Delayed (exclamation) expansion occurs at run time (2nd)
The search and replace terms must be expanded before the search and replace can take place. So you want:
set str=!str:%original%=%replacement%!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With