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

Laurence Brown picture Laurence Brown · Apr 25, 2013 · Viewed 8.8k times · Source

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.

Answer

PA. picture PA. · Apr 25, 2013

The code you have posted is just trying to replace the values in the filename, not in the contents of the file.

You need to change the code in order to find and replace inside the content of the file.

To achieve this, you need to (1) read the file (2) find and replace the string and (3) write back

  1. you have to read the file. Use the FOR command. Read HELP FOR and try the following code.

    for /f "tokens=*" %%a in (%hostpath%\%hostfile%) do (
      echo %%a
    )
    
  2. find and replace

    for /f "tokens=*" %%a in (%hostpath%\%hostfile%) do (
      set string=%%a
      set string=!string:%find%=%replace%!
      echo !string!
    )
    
  3. you have to write the results back to the file. Redirect the output of the echo to a temporary file and then replace the original file with the temporary file

    echo. >%temp%\hosts
    for /f "tokens=*" %%a in (%hostpath%\%hostfile%) do (
      set string=%%a
      set string=!string:%find%=%replace%!
      echo !string! >>%temp%\hosts
    )
    copy %temp%\hosts %hostpath%\%hostfile%