omidoslo
omidoslo

Reputation: 1

Delete 2 Lines From hosts

I need to remove 2 lines from my hosts file in a Batch File:

www.domain1.com
www.domain2.com

So I wrote this code, but have some problems:

@Echo Off
Set hosts=%WinDir%\System32\Drivers\etc\hosts
Attrib -R %hosts%

FindStr /V /I /C:"www.domain1.com" "%hosts%" > "d:\1.txt"
FindStr /V /I /C:"www.domain2.com" "d:\1.txt" > "d:\2.txt"

Well this work and d:\2.txt is made the way I want, so now I must delete 1.txt and replace/move 2.txt to hosts I have some questions to update and make my code simpler:

Can I merge the above 2 FindStr lines into 1 line without making a 3rd file? I don't know why for example this one does not work, while it should work?

FindStr /V /I /C:"www.domain1.com" "%hosts%" > "%hosts%"

This makes the whole file empty! Please advise, not using Find :)

Upvotes: 0

Views: 1276

Answers (1)

Mofi
Mofi

Reputation: 49087

The complete command line to search case-insensitive and literally in all lines in hosts file for either www.r2rdownload.com or www.elephantafiles.com and output all lines not containing one of those two strings is:

%SystemRoot%\System32\findstr.exe /I /L /V "www.r2rdownload.com www.elephantafiles.com" "%SystemRoot%\System32\drivers\etc\hosts"

The option /L is important as otherwise the two strings separated by a space are interpreted as regular expression strings with . being interpreted as placeholder for any character except newline character.

Another possibility for exactly the same find result is:

%SystemRoot%\System32\findstr.exe /I /V /C:"www.r2rdownload.com" /C:"www.elephantafiles.com" "%SystemRoot%\System32\drivers\etc\hosts"

The command line to find additionally empty lines anywhere in file and so do not output those lines is:

%SystemRoot%\System32\findstr.exe /I /R /V "www\.r2rdownload\.com www\.elephantafiles\.com ^$" "%SystemRoot%\System32\drivers\etc\hosts"

All three space separated strings are regular expression strings in this case which is the reason for escaping . with a backslash character to be interpreted as literal character.

The entire batch file could be for example:

@echo off
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
%SystemRoot%\System32\attrib.exe -r "%HostsFile%"
%SystemRoot%\System32\findstr.exe /I /R /V "www\.r2rdownload\.com www\.elephantafiles\.com ^$" "%HostsFile%" >"%TEMP%\%~n0.tmp"
move /Y "%TEMP%\%~n0.tmp" "%HostsFile%"
if errorlevel 1 del "%TEMP%\%~n0.tmp"
set "HostsFile="

This batch file must be executed with elevated privileges of an administrator.

Upvotes: 1

Related Questions