1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Find and Replace a string using batch

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

  1. Cleptography

    Cleptography New Member

    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