Search code examples
batch-fileedithostshosts-file

How to replace a string in the host file using batch?


I'm trying to write a batch file to find and replace an IP address in the hosts file.

I did a bit of research and found this, but it doesn't seem to work. I get the final echo of "Done." but it doesn't work.

@echo off

REM Set a variable for the Windows hosts file location
set hostpath=%systemroot%\system32\drivers\etc
set hostfile=hosts

REM Make the hosts file writable
attrib -r %hostpath%\%hostfile%

setlocal enabledelayedexpansion
set string=%hostpath%\%hostfile%

REM set the string you wish to find
set find=OLD IP

REM set the string you wish to replace with
set replace=NEW IP
call set string=%%string:!find!=!replace!%%
echo %string%

REM Make the hosts file un-writable
attrib +r %hostpath%\%hostfile%

echo Done.

Solution

  • @echo off
    
    REM Set a variable for the Windows hosts file location
    set "hostpath=%systemroot%\system32\drivers\etc"
    set "hostfile=hosts"
    
    REM Make the hosts file writable
    attrib -r -s -h "%hostpath%\%hostfile%"
    
    REM set the string you wish to find
    set find=OLD IP
    REM set the string you wish to replace with
    set replace=NEW IP
    
    setlocal enabledelayedexpansion
    for /f "delims=" %%a in ('type "%hostpath%\%hostfile%"') do (
    set "string=%%a"
    set "string=!string:%find%=%replace%!"
    >> "newfile.txt" echo !string!
    )
    
    move /y "newfile.txt" "%hostpath%\%hostfile%"
    
    REM Make the hosts file un-writable - not necessary.
    attrib +r "%hostpath%\%hostfile%"
    
    echo Done.
    pause