找到一个单词并用批处理文件替换一行



我的Windows XP虚拟机上有一台本地服务器。

每次我的主网络从wifi变为有线电视,或者我转移到不同的网络时,我的Win XP盒子的IP都会发生变化。

我想运行一个批处理文件,将新的IP映射到我的主机文件中的一些通用名称

C:WINDOWSsystem32driversetchosts

例如,如果我现在有:

10.97.100.74 www.myAppServer.com

并且如果ip改变为CCD_ 3,我想在hosts文件中搜索字符串myAppServer,并用替换整行

192.168.11.9 www.myAppServer.com

我能够获得当前的IP使用:

for /f "skip=1 delims={}, " %%A in ('wmic nicconfig get ipaddress') do for /f "tokens=1" %%B in ("%%~A") do set "IP=%%~B"
set IP=%IP%

但是我该如何找到并替换它呢?

我在DOS提示上发现了这个

BatchSubstitute-逐行解析文件并替换子字符串

@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION
::BatchSubstitute - parses a File line by line and replaces a substring
::syntax: BatchSubstitute.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
::$changed 20100115
::$source http://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo.
)

如果你想只替换一行,你可以这样做:

@echo off
setlocal
cd "C:WINDOWSsystem32driversetc"
for /F "delims=:" %%a in ('findstr /N "myAppServer" hosts') do set lineNum=%%a
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" hosts') do (
   if %%a equ %lineNum% (
      echo 192.168.11.9 www.myAppServer.com
   ) else (
      echo %%a
   )
)) > hosts.new

如果主机文件包含Batch特殊字符(如| > < & !),此程序将消除空行,并且会出现问题。如果需要,这些细节可能是固定的。

最简单的方法是不替换它。删除它并添加新行。

如果你的ip地址在%ip%,那么

set "hostsFile=%systemroot%system32driversetchosts"
(
    findstr /v /i /c:"www.MyAppServer.com" "%hostsFile%"
    echo(
    echo %IP% www.MyAppServer.com
) > "%temp%hosts"
move /y "%temp%hosts" "%hostsFile%" >nul 2>nul

请确保您有足够的权限更改主机文件,并且没有防病毒软件阻止对其进行更改。

这终于完成了任务:

@echo off
REM Set a variable for the Windows hosts file location
set "hostpath=%systemroot%system32driversetc"
REM set "hostpath=C:projectStarProgramsetc" 
set "hostfile=hosts"
REM Make the hosts file writable
attrib -r -s -h "%hostpath%%hostfile%"
for /f "skip=1 delims={}, " %%A in ('wmic nicconfig get ipaddress') do for /f "tokens=1" %%B in ("%%~A") do set "IP=%%~B"
REM echo %IP%
set IP=%IP%
move /y "%hostpath%%hostfile%" "Hs.txt"
findstr /v/c:"www.nexsoftnetwork.com" Hs.txt > "Hss2.txt"
echo %IP%   www.nexsoftnetwork.com >>"Hss2.txt"
move /y "Hss2.txt" "%hostpath%%hostfile%"
echo Done.
pause

感谢大家的投入。但我想从我的手机上访问这个服务器,它将与服务器在同一网络上。最后我注意到,除非我修改主机操作系统或手机的主机文件,否则它仍然无法解决我的问题。只有当我想在虚拟机箱中使用此服务器时,此解决方案才有效。

最新更新