Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Programming (http://www.go4expert.com/forums/programming-forum/)
-   -   Find and Replace a string using batch (http://www.go4expert.com/forums/replace-string-using-batch-t25271/)

Cleptography 17Mar2011 12:21

Find and Replace a string using batch
 
This will find all occurrences of a specified string and replace them.

TXT File
Code:

Hello world this is a test
Hello WoRlD this is a test
Hello Planet this is a test
Hello Dolly f**k off vermon

Script
Code:

@echo off
 setlocal

set file=%~1

for /f "tokens=*" %%- in (%file%) do (
    set str=%%-&&call :NEXT
)
goto :eof

:NEXT
set str=%str:world=planet%
echo.%str%>>New_%file%
goto :eof

In this case all the world strings will be replaced with planet.
This option below will except command line arguments.
Syntax:
ScriptName.bat "Str2LookFor" "Str2RepWith" "File2Search.txt"
Code:

@echo off
 setlocal enabledelayedexpansion

set strR=%~1
set strW=%~2
set file=%~3

for /f "tokens=*" %%- in (%file%) do (
        set str=%%-&&call :NEXT
)
goto :eof

:NEXT
set str=!str:%strR%=%strW%!
echo.%str%
goto :eof



All times are GMT +5.5. The time now is 01:06.