I am trying to edit the hosts file to remove the lines containing #AntiSpam
In order not to do the tests on the host directly, I have created another text document on which to do the tests and I have called it document.txt
# Copyright (c) 1993-2009 Microsoft Corp.
#
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
0.0.0.0 meetsexpartners13.com #AntiSpam
0.0.0.0 pqdlj.dateszone.net #AntiSpam
0.0.0.0 thebestgame2020.com #AntiSpam
0.0.0.0 hotdatinghookups.com #AntiSpam
## Local by Flywheel - Start ##
::1 testing.local #Local Site
127.0.0.1 testing.local #Local Site
::1 www.testing.local #Local Site
127.0.0.1 www.testing.local #Local Site
## Local by Flywheel - End ##
For this I proposed to do a line-by-line reading of the text document:
@echo off
FOR /F "tokens=*" %%A IN (documento.txt) DO @ECHO Linea: %%A
pause>nul
And when reading the line with a conditional check if it contains the string #AntiSpam
@echo off
set linea=0.0.0.0 meetsexpartners13.com #AntiSpam
if "%linea%"=="%linea:#AntiSpam=%" (
echo No contiene
) else (
echo Lo contiene
)
pause>nul
But when joining them I have problems
@echo off
FOR /F "tokens=*" %%A IN (documento.txt) DO (
set linea=%%A
if "%linea%"=="%linea:#AntiSpam=%" (echo %%A)
)
pause>nul
Problem
Although it seems to me that everything should work fine for some reason I cannot save the variable %%A inside line , at least as I am doing it it remains blank.
I do it by saving it because I can't do the %line:#AntiSpam=% directly on %%A or at least I don't know how it would be done.
Warning
I know that at the moment I am not editing the document, I would only be printing the lines in the console. Later when I solve this I will get to that, I guess I will create a temporary file on which to dump the filtered data and after removing everything I will replace the content of document.txt with the temporary one which when I finish passing I will delete.
Although if someone can tell me a better way than this I'm doing great.
In Linux I would do it like this from the command line (or you put it in a bash):
where:
cat host
: print the file in the outputhost
grep -v "#AntiSpam"
: If it finds the string#AntiSpam
, it skips the line and does not show it, otherwise it shows the line> nuevo_host
: Redirect everything to a new file callednuevo_host
On Windows I guess it should be something like this (I don't use or have Windows, I can't test it):
Try it and if it works you can put it in a bat.