String replacement in a batch file

As a developer, the most of us usually need to script commands to make our lives easier. I had this scenario where I needed to use variables in a batch file that I wrote. For the sake of simplicity, I’m changing the script and the variable names so that its easier to understand. I asked this question on stackoverflow.com and got more than one method of achieving it. Here we have both methods explained.

Replacing a word with another word:

So the first thing is that here is a simple script that replaces a word with another word in a string.

echo off
set str="jump over the chair"
set str=%str:chair=table%

echo %str%

When we execute these lines in a batch file, we see that the word ‘chair’ in the given string was replaced with the word ‘table’.

Replacing a word with a variable value:

Now moving next, what if we have a variable whose value needs to be replaced at runtime. For example, we have the following script similar to the script above but with a change that the word ‘table’ is not a constant anymore. It is assigned to a variable ‘word’ and the value of that variable needs to be set in place of the word ‘chair’.

We can achive this using two methods.

Method 1: Using delayed expansion (!variable!)

echo off
setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%
echo %str%

Method 2: Using advanced variable substitution

Using the CALL command, we can expand a variable located in the same line. This can deliver multilevel expansion, by repeated CALL and modifier use.

echo off
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

I asked this question on www.stackoverflow.com some years back.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: