Find and Replace a string using batch

Discussion in 'Programming' started by Cleptography, Mar 17, 2011.

  1. Cleptography

    Cleptography New Member

    Joined:
    Sep 2, 2010
    Messages:
    39
    Likes Received:
    7
    Trophy Points:
    0
    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
     
    Last edited: Mar 17, 2011

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice