在BAT文件脚本中,如果FILE不包含该行

时间:2018-01-25 13:16:41

标签: windows batch-file hosts

我想在hosts文件中添加一行:

127.0.0.1       new-host

如果它不包含此行。

windows中使用bat脚本。

示例1

脚本前的

127.0.0.1       db
127.0.0.1       host

脚本之后:

127.0.0.1       db
127.0.0.1       host
127.0.0.1       new-host

示例2

脚本前的

127.0.0.1       db
127.0.0.1       host
127.0.0.1       new-host

脚本之后:

127.0.0.1       db
127.0.0.1       host
127.0.0.1       new-host

我的代码:

for /f "delims=" %%i in ('findstr /c:"new-host" "c:\Windows\System32\Drivers\etc\hosts"') do set actualLineHost=%%i
echo %actualLineHost%

if "%actualLineHost:"=.%"==".." (
    echo empty
    goto empty
) else (
    echo not empty
    goto notempty
)

findstr /c:"new-host" "c:\Windows\System32\Drivers\etc\hosts"在命令行中运行正常,但是当我运行脚本时,当文件不包含行时,它“不为空”。

2 个答案:

答案 0 :(得分:2)

试试这段代码:

@echo off
findstr /m "new-host" C:\Windows\System32\drivers\etc\hosts
if %errorlevel%==0 (
echo Found!
) else (
echo No matches found
echo 127.0.0.1       new-host >> C:\Windows\System32\drivers\etc\hosts
)
pause

这将启动findstr cmd来搜索文件中的一个(或多个)定义字符串,在此之后,我们检查命令是否返回错误,是否没有错误,我们做了一个echo来写入文件中的行(>>用于换行)

答案 1 :(得分:0)

不使用errorlevel

的解决方案
for /f "delims=" %%i in ('findstr /c:"new-host" "c:\Windows\System32\Drivers\etc\hosts"') do goto hostContains
echo 127.0.0.1       new-host >> c:\Windows\System32\Drivers\etc\hosts
echo "Not found"
goto exit

:hostContains
echo "Found"
:exit