You are here:Home»KB»PC»Windows Family»Replace a text string in a Windows Batch file
Saturday, 30 July 2022 12:47

Replace a text string in a Windows Batch file

Written by

This can be tricky if you do not know how to do this, it should also be noted depending on what text you are replacing your method you will use will change.

These methods can also be used to remove text from strings.

Standard Text String Replacement

This is straight forward and you should just use the example below. This will not allow the use of %

@echo off

set mystring=This is a water bottle. 
echo %mystring% 

set mystring=%mystring:water=glass%
echo %mystring%

Outputs as follows:

This is a water bottle.

-->

This is a glass bottle.

 

% Character and String Replacement

To replace % you need to do a few more steps because % is a special character. This method will also allow you to change normal strings aswell.

The following example will convert a URL that has had the slashes replaced with HTML entities and of course these include % which is a special character in batch files and cannot be escaped.

We use EnableDelayedExpansion to change when these variables are parsed allowing us to convert the %5C to \ so the URL can be used appropriately. We are just using echo here but the variable can be used like normal variable aswell.

The example will convert the following URL

D:%5Cwebsites%5Chtdocs%5Cprojects%5Cqwcrm%5Csrc%5Ccache%5Csmarty%5Ccompile%5Cd0d7cab3fc900.file.financial.tpl.php

-->

D:\websites\htdocs\projects\qwcrm\src\cache\smarty\compile\d0d7cab3fc900.file.financial.tpl.php

The Example

@echo off

:: Each variable is to be expanded at execution time rather than at parse time
setlocal EnableDelayedExpansion

:: Set the URL that has been passed to the batch file as a commandline parameter
set URL=%1

:: Convert '%5C' --> '\' - Notice the command is wrapped in !
set URL=!URL:%%5C=\!

:: Optional
endlocal

:: Output the URL
echo %URL%

 

Links

Read 4482 times Last modified on Saturday, 30 July 2022 14:45