Reputation: 1221
I want to add one line in hosts
file:
127.0.0.1 new-host
if it doesn't contain this line.
In windows
use bat
scripting.
Example 1
before script:
127.0.0.1 db
127.0.0.1 host
after script:
127.0.0.1 db
127.0.0.1 host
127.0.0.1 new-host
Example 2
before script:
127.0.0.1 db
127.0.0.1 host
127.0.0.1 new-host
after script:
127.0.0.1 db
127.0.0.1 host
127.0.0.1 new-host
My code:
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"
works fine in command line returns nothing, but when I run a script a have "not empty" when file doesn't contain line.
Upvotes: 0
Views: 460
Reputation: 1221
Solution without using 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
Upvotes: 0
Reputation: 2698
Try this code :
@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
This will launch findstr cmd to search one (or more ) define string in a file, after this, we check if command return error or not, is there is no error, we made an echo to write the line in the file ( >> is for going new line )
Upvotes: 2