Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file substring replacement using variables

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.

like image 734
delpium Avatar asked Aug 09 '12 22:08

delpium


People also ask

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.

What does %% A mean in batch?

%%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.

How to replace a string in cmd?

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).

What is %% P in batch file?

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.


2 Answers

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%

like image 127
azhrei Avatar answered Sep 17 '22 17:09

azhrei


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%!
like image 30
dbenham Avatar answered Sep 18 '22 17:09

dbenham