如何更换使用批处理主机文件的字符串? [英] How to replace a string in the host file using batch?

查看:165
本文介绍了如何更换使用批处理主机文件的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个批处理文件查找和主机文件替换IP地址。

我做了一些研究,发现这一点,但它似乎并没有工作。我得到的最后的回声完成。但它不工作。

 关闭@echoREM设置为Windows变量主机文件位置
集hostpath =%SYSTEMROOT%\\ SYSTEM32 \\ drivers \\ etc下
设置HOSTFILE =主机REM使hosts文件写
ATTRIB -r%hostpath%\\%HOSTFILE%SETLOCAL enabledelayedexpansion
组字符串=%hostpath%\\%HOSTFILE%REM设置想要查找的字符串
设置查找=旧的IPREM设置想要用来替换字符串
集替换=新的IP
呼叫建立字符串= %%字符串:!!!!找到替换= %%
回声%字符串%REM使hosts文件未写
ATTRIB + R%hostpath%\\%HOSTFILE%回声完成。


解决方案

 关闭@echoREM设置为Windows变量主机文件位置
集hostpath =%SYSTEMROOT%\\ SYSTEM32 \\ drivers \\ etc下
设置HOSTFILE =主机REM使hosts文件写
ATTRIB -r -s -h%hostpath%\\%HOSTFILE%REM设置想要查找的字符串
设置查找=旧的IP
REM设置想要用来替换字符串
集替换=新的IPSETLOCAL enabledelayedexpansion
FOR / Fdelims =%%一中(类型%hostpath%\\%HOSTFILE%')做(
设置字符串= %%一个
设置字符串=字符串:%!找到%=%替换%!
>> newfile.txt回声!串!
)移动/ Ynewfile.txt%hostpath%\\%HOSTFILE%REM使hosts文件未写的 - 没有必要的。
ATTRIB + R%hostpath%\\%HOSTFILE%回声完成。
暂停

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.

解决方案

@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

这篇关于如何更换使用批处理主机文件的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆