Batch Script – Replace a String
Last Updated :
28 Nov, 2021
Improve
In this article, we are going to Replace a substring with any given string.
Batch Script :
@echo off set str=GFG is the platform for geeks. echo %str% set str=%str:the=best% echo %str% pause
In the above example, we are going to replace ‘the’ by substring ‘best’ using %str:the=best% statement.
Explanation :
- By using ‘ set ‘ we are getting input of any string
set str=input string
- In the next line using ‘ echo %str% ‘ we are printing our string.
- Using ‘ %str:the=best%’ statement , we are replacing substring ‘the’ with ‘best’.
- Then using ‘pause’, to hold the screen until any key is pressed, so that we can read our output.
Output :
‘the’ is replaced by ‘best’
Another Approach :
Batch Script :
@echo off set str=GFG is the platform for geeks. set word=best echo %str% call set str=%%str:the=%word%%% echo %str% pause
Explanation :
- Everything is as same as before, we are trying to replace the word ‘the’ with ‘best’ but we can also do this by calling another variable ‘word’ which is equal to ‘best’.
- By using call there is another layer of variable expansion so we have to use ‘%’ for ‘word’ so that it will use ‘best’ as its value and replace the string.
output by 2nd approach