L. Young
L. Young

Reputation: 173

Remove line from hosts file through BAT script

I have written a bat script which will add a line to a hosts file. However I also want to delete any lines which already have the same address. For example:

Add lines 192.168.1.1 wwww.google.com

I want to check if there is already a line with www.google.com and remove it.

Can someone explain how to do this please?

My .bat to append a line. I need to edit it to first delete a line then add this one.

@ECHO off
ECHO. >> %WinDir%\System32\drivers\etc\hosts
FINDSTR /V "217.168.173.1" "%WinDir%\system32\drivers\etc\hosts"
ECHO 123.456.7.1   www.google.com >> %WinDir%\system32\drivers\etc\hosts
EXIT

Upvotes: 0

Views: 13462

Answers (2)

Use copy instead of MOVE to reserve the access rights

@ECHO off
SETLOCAL
SET "HOSTS=%WinDir%\System32\drivers\etc\hosts"
SET "TEMP_HOSTS=%TEMP%\%RANDOM%__hosts"
FINDSTR /V "217.168.173.1" "%HOSTS%" > "%TEMP_HOSTS%"
ECHO 123.456.7.1   www.google.com >> "%TEMP_HOSTS%"
COPY /b/v/y "%TEMP_HOSTS%" "%HOSTS%"
EXIT /B

Upvotes: 0

mojo
mojo

Reputation: 4132

Use findstr.exe to filter out lines (/V).

FINDSTR /V "192.168.1.1" "%HOSTS%"

This will output the contents of %HOSTS% without any lines containing 192.168.1.1. This won't tell you if the line you wanted to filter was in the file or not, but will give you a file without that address in it. After that, you could always add the address to the end of the file (e.g. ECHO 192.168.1.1 www.google.com >>%HOSTS%), being certain that it's not already there.

UPDATE

A modification of your work in progress:

@ECHO off
SETLOCAL
SET "HOSTS=%WinDir%\System32\drivers\etc\hosts"
SET "TEMP_HOSTS=%TEMP%\%RANDOM%__hosts"
FINDSTR /V "217.168.173.1" "%HOSTS%" > "%TEMP_HOSTS%"
ECHO 123.456.7.1   www.google.com >> "%TEMP_HOSTS%"
MOVE /Y "%TEMP_HOSTS%" "%HOSTS%"
EXIT /B

Changes:

  • SETLOCAL prevents env var changes from affecting the calling CMD session.
  • Save the location of the file to a variable.
  • Save the output of the filtering command (FINDSTR) to a temp file (making all changes to the temp file).
  • Replace the production hosts file with the newly-created temp file.
  • EXIT /B will exit the script without ending your CMD session (when run interactively—i.e. testing/development).

Upvotes: 0

Related Questions