我正在尝试编写批处理文件来查找和替换hosts文件中的IP地址。
我做了一些研究并找到了这个,但它似乎没有用。我得到了“完成”的最终回声。但它不起作用。
@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.
答案 0 :(得分:1)
您发布的代码只是尝试替换文件名中的值,而不是文件内容中的值。
您需要更改代码才能在文件内容中查找和替换。
要实现这一点,你需要(1)读取文件(2)查找并替换字符串并(3)回写
您必须阅读该文件。使用FOR
命令。阅读HELP FOR
并尝试以下代码。
for /f "tokens=*" %%a in (%hostpath%\%hostfile%) do (
echo %%a
)
查找并替换
for /f "tokens=*" %%a in (%hostpath%\%hostfile%) do (
set string=%%a
set string=!string:%find%=%replace%!
echo !string!
)
您必须将结果写回文件。将echo的输出重定向到临时文件,然后用临时文件
替换原始文件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%
答案 1 :(得分:0)
@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 :(得分:-1)
这样可行。
call set newstring=%string:%find%=%replace%%
将结果值分配给新字符串。