Batch Script – Replace a String
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 Beginner. 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 :
Another Approach :
Batch Script :
@echo off set str=GFG is the platform for Beginner. 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.
Contact Us