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

 ̄綄美尐妖づ 提交于 2019-12-24 01:43:11

问题


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.

回答1:


@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



回答2:


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%
    



回答3:


This will work.

call set newstring=%string:%find%=%replace%%

Assign the resultant value to a new string.



来源:https://stackoverflow.com/questions/16208429/how-to-replace-a-string-in-the-host-file-using-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!