如何使用批处理替换主机文件中的字符串



我正试图写一个批处理文件来查找和替换主机文件中的IP地址。

我做了一些研究,发现了这个,但它似乎不起作用。我听到了最后的回音"搞定"但不管用。

@echo off
REM Set a variable for the Windows hosts file location
set hostpath=%systemroot%system32driversetc
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)读取文件(2)查找并替换字符串以及(3)回写

  1. 你必须读取文件。使用FOR命令。阅读HELP FOR并尝试以下代码:

    for /f "tokens=*" %%a in (%hostpath%%hostfile%) do (
      echo %%a
    )
    
  2. 查找并替换

    for /f "tokens=*" %%a in (%hostpath%%hostfile%) do (
      set string=%%a
      set string=!string:%find%=%replace%!
      echo !string!
    )
    
  3. 必须将结果写回文件。将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%
    
@echo off
REM Set a variable for the Windows hosts file location
set "hostpath=%systemroot%system32driversetc"
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

可以。

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

将结果值赋给新字符串。

相关内容

  • 没有找到相关文章

最新更新