# Batch file to scan .txt



## silentmage (Oct 25, 2007)

I am familiar with how to populate a .txt with a batch files, but is it possible for a batch file to scan one looking for specific text, if it is not there append it with what I want? I am the tech specialist for 2 schools and I need a quick and easy way to edit the hosts file on a large amount of computers so they register on my server and not another schools.

eg....

it has...

10.17.128.51 zenwsimport


and it should have

10.18.128.51 zenwsimport


so it see's the 10.17 line, deletes it, and adds the 10.18 line. Maybe too complicated for batch files?


----------



## Ent (Apr 11, 2009)

I think this ought to be possible.

Basically all you want to do is run through every line of the hosts file and put the IP you want at the front of it, the previous IP can effectively be ignored. I reckon that you could accomplish this with a for command.
Something like the following would do it very simple, note that it would remove any comments, and also can't handle IPv6.


```
@echo off
PushD C:\Windows\System32\Drivers\Etc
echo Reparsing IPs.
for /F "EOL=# tokens=2" %%l in (hosts) do (
echo 10.18.128.51    %%l >> Hosts.new
)
Rename Hosts Hosts.old
Rename Hosts.new Hosts

Echo Reparse Complete.
Pause
```


----------



## Squashman (Apr 4, 2003)

I worked on a Novell network for several years but that was ages ago and I know there is a better way to do what you want to do then the way you are doing it. We had a Zenworks server for each of of the schools (High school. Junior High & elementary) because they were so far apart from each other. Rural school district. Was alot easier to image the schools computer with Zenworks loaded on one of the local servers vs the one at the high school. I know there is a way to get them to register on the local zen server without having to edit the hosts file to force them to look at your zen server. In fact we even had them registered into different OU's in the tree so that we could really micro manage them.

I have a friend who still manages a Novell network. I will see if he can give me a clue as to what you have misconfigured


----------



## TheOutcaste (Aug 8, 2007)

This will replace 10.17.128.51 with 10.18.128.51, or add it if missing.
It will preserve all comments
It will preserve all other entries

On Vista/Win 7, you have to Right click the file, then click Run as Administrator, or run it from an Admin (Elevated) Command Prompt.

```
@Echo Off
SetLocal EnableDelayedExpansion
PushD %SystemRoot%\System32\Drivers\Etc
Echo Reparsing IPs.
Set _Found=0
For /F "tokens=* Delims=" %%l In (hosts) Do (
Echo.%%l|Findstr "10.17.128.51">Nul
If !Errorlevel!==1 (
>>Hosts.new Echo.10.18.128.51       zenwsimport
Set _Found=1
) Else (
>>Hosts.new Echo.%%l
)
Echo.%%l|Findstr "10.18.128.51">Nul
If !Errorlevel!==0 Set _Found=1
)
If %_Found%==0 >>Hosts.new Echo.10.18.128.51       zenwsimport
Rename Hosts Hosts.old
Rename Hosts.new Hosts

Echo Reparse Complete.
Pause
PopD
```


----------



## TRS-80 vet (Jun 18, 2005)

```
Findstr "10.17.128.51">Nul
```
This means 'Find code string "10.xxx.51", ???

and >Nul means to ignore any characters/digits that follow "10.xxx.51" ???

-------------------------

In this script, what is the location of the .txt file in which the changes will made?

----------------------

%%A - This means 'Every item' ? 
What does - %%l signify?


----------



## TheOutcaste (Aug 8, 2007)

TRS-80 vet said:


> ```
> Findstr "10.17.128.51">Nul
> ```
> This means 'Find code string "10.xxx.51", ???


This means search the text piped from the Echo command to Findstr for the text string 10.17.128.51



TRS-80 vet said:


> and >Nul means to ignore any characters/digits that follow "10.xxx.51" ???


> is the redirection symbol. When no handle is specified, it redirects STDOUT (which is handle 1) to another device, in this case *Nul*, or nothing. *Findstr* echos any line that has matching text to the screen; this prevents that from appearing.



TRS-80 vet said:


> In this script, what is the location of the .txt file in which the changes will made?


While *Hosts* is a text file, it has no extension
The location is the current directory, set by *PushD* to 
*%SystemRoot%\System32\Drivers\Etc*
*%SystemRoot%* is the folder that contains the Operating System, usually named Windows, and usually on the C: drive.


TRS-80 vet said:


> %%A - This means 'Every item' ?
> What does - %%l signify?


There is no %%A in this file.
The %%l (lowercase L) is just the loop variable that holds the current item from the set, which in this case is the lines in the *Hosts* file.


----------



## Ent (Apr 11, 2009)

err, Outcaste, your batch doesn't record the original domain name. You just get a gazillion lines of redirect zenwsimport to 10.18.128.51. 

On my machine I'm also getting 'Destroy' is not recognized as an internal or external command,
operable program or batch file, and don't keep the comments.


----------



## TheOutcaste (Aug 8, 2007)

Arg, you are right, don't know how it happened, somehow the errorlevel check got changed from 0 to 1. (correction shown in red)

It also doesn't check to see if a Host.new or hosts.old file already exits. This version checks for that, and adds date and time to the old name so it can be run multiple times on the same system without losing any previous version of the hosts file, and fixes the error level check.
This should work correctly:

```
@Echo Off
SetLocal EnableDelayedExpansion
PushD %SystemRoot%\System32\Drivers\Etc
If Exist Hosts.new Del Hosts.new
Echo Reparsing IPs.
Set _Found=0
For /F "tokens=* Delims=" %%l In (hosts) Do (
  Echo.%%l|Findstr "10.17.128.51">Nul
  If !Errorlevel!==[COLOR=Red]0[/COLOR] (
    >>Hosts.new Echo.10.18.128.51       zenwsimport
    Set _Found=1
  ) Else (
    >>Hosts.new Echo.%%l
  )
  Echo.%%l|Findstr "10.18.128.51">Nul
  If !Errorlevel!==0 Set _Found=1
)
If %_Found%==0 >>Hosts.new Echo.10.18.128.51       zenwsimport
Set _Date=%date%%time%
Set _Date=%_Date: =%
Set _Date=%_Date:/=-%
Set _Date=%_Date::=-%
Rename Hosts %_Date%Hosts.old
Rename Hosts.new Hosts

Echo Reparse Complete.
Pause
PopD
```


----------



## Ent (Apr 11, 2009)

Well it now keeps the comments, but still changes all host names to zenwsimport.


----------



## TheOutcaste (Aug 8, 2007)

I have know idea why it's changeing hosts names for you. I just ran the batch file against the 16,556 line MVP Hosts file, and *zenwsimport* only appears once.

Ran this on Win 7 Ultimate x64 and XP Honme SP3

Did a file Comparison using FC and there are only 5 differences (identical under both OSes), none that would effect the usage of the file (except the added/changed *zenwsimport* line of course):


 2 Blank Lines Removed
 Text between 2 Exclamation points in a comment was removed
 1 Blank Line Removed
 Exclamation point in a Comment Removed
 1 Blank Line Removed and the new line added.
 Blue is the original file, green is the new file.

```
[B]C:\Test>[/B]FC /L Hosts %Userprofile%\Desktop\Hosts
Comparing files Hosts and C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
[COLOR=Indigo][B]2 Blank Lines Removed[/B][/COLOR]
[COLOR=DarkGreen]*****Hosts
# http://creativecommons.org/licenses/by-nc-sa/3.0/        #
127.0.0.1  localhost
#start of lines added by WinHelp2002[/COLOR]
[COLOR=Blue]***** C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
# http://creativecommons.org/licenses/by-nc-sa/3.0/        #

127.0.0.1  localhost

#start of lines added by WinHelp2002
*****[/COLOR]

[COLOR=Indigo][B]Text between Exclamation points in the comment was removed[/B][/COLOR]
[COLOR=DarkGreen]***** Hosts
127.0.0.1  upd.dns-look-up.com
127.0.0.1  o21343.nb.host-domain-lookup.com #[McAfee.Swizzor87ad9031ef7d]
127.0.0.1  lop.com #[Wildcard DNS][/COLOR]
[COLOR=Blue]***** C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
127.0.0.1  upd.dns-look-up.com
127.0.0.1  o21343.nb.host-domain-lookup.com #[McAfee.Swizzor[B][COLOR=Red]!hv.j![/COLOR][/B]87ad9031ef7d]
127.0.0.1  lop.com #[Wildcard DNS]
*****[/COLOR]

[COLOR=Indigo][B]1 Blank Line Removed[/B][/COLOR]
[COLOR=DarkGreen]***** Hosts
127.0.0.1  internetretailer.d2.sc.omtrdc.net
127.0.0.1  metrics.rcsmetrics.it[/COLOR]
[COLOR=Blue]***** C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
127.0.0.1  internetretailer.d2.sc.omtrdc.net

127.0.0.1  metrics.rcsmetrics.it
*****[/COLOR]

[COLOR=Indigo][B]Exclamation point in a Comment Removed[/B][/COLOR]
[COLOR=DarkGreen]***** Hosts
127.0.0.1  www.idolove.com #[Win32/AdInstaller]
127.0.0.1  www.intwined.com #[McAfee.Adware-SSFHosts]
127.0.0.1  www.malwhere.com[/COLOR]
[COLOR=Blue]***** C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
127.0.0.1  www.idolove.com #[Win32/AdInstaller]
127.0.0.1  www.intwined.com #[McAfee.Adware-SSF[B][COLOR=Red]![/COLOR][/B]Hosts]
127.0.0.1  www.malwhere.com
*****[/COLOR]

[COLOR=Indigo][B]1 Blank Line Removed and the new line added.[/B][/COLOR]
[COLOR=DarkGreen]***** Hosts
#end of lines added by WinHelp2002
[COLOR=DarkRed]10.18.128.51       zenwsimport[/COLOR][/COLOR]
[COLOR=Blue]***** C:\USERS\THEOUTCASTE\DESKTOP\HOSTS
#end of lines added by WinHelp2002

*****[/COLOR]

[B]C:\Test>[/B]
```
Comment out the Echo Off line, then let it run for a couple seconds then hit CTRL+C to pause, then maybe you can see why it's doing that on your system.


----------



## Ent (Apr 11, 2009)

I will leave it to the OP to say his situation; it is entirely possible that his computer is parsing it as your is. On my part, the only edits I made to your original were removing the PushD to let me work on a test hosts file. I also ran a find and replace against the hosts file itself from the localhost IP to the 10.17.128.51 provided.

Here's a few lines from the folder now called Hosts on my desktop.


> # 102.54.94.97 rhino.acme.com # source server
> # 38.25.63.10 x.acme.com # x client host
> 10.18.128.51 zenwsimport
> ::1 localhost
> ...


I also still got the two lines of Destroy is not recognized.


----------



## TheOutcaste (Aug 8, 2007)

The first version would have spewed out that same line repeatedly, and if the program didn't complete, that Hosts.New file would be left behind. If it doesn't get deleted, the next run gets appended, so you'd see that same start all the time. This last version deletes the file, so that shouldn't happen, unless the duplicates are in the original file, as this will not remove any duplicates.

One thing that comes to mind, as I've done it more than once, are you sure you are looking at the same file the program is changing? I've setup tests with two folders, Test and Test1, keeping original copies in one folder to start over with. I open up the original in *Test1* by mistake, then try to figure out why it's not being changed. The batch file of course was changing the file in *Test*

The Destroy error is because of the *&* in this line:
*Echo.# Start of entries inserted by Spybot - Search & Destroy|Findstr...*
The & is a Special Character, used to separate multiple commands on one line.
So the line is seen as this:
*Echo.# Start of entries inserted by Spybot - Search*
*Destroy|Findstr...*

Destroy is not a valid command, so it generates the error, and since it's on the same line, the Echo never happens either.
It does get echoed to the file correctly. Just one of the quirks when dealing with the special characters.


----------



## Ent (Apr 11, 2009)

That does explain the whole destroy business.
This is the same area from my old hosts file, timed and dated. I don't know why there's a difference. I'm actually testing each of your scripts with a new copy of hosts. Maybe my computer's just in a bad mood. 


> # 102.54.94.97 rhino.acme.com # source server
> # 38.25.63.10 x.acme.com # x client host
> 10.17.128.51 localhost
> ::1 localhost
> ...


----------



## TheOutcaste (Aug 8, 2007)

Well, all of those lines have the *10.17.128.51* IP address, so they will all get changed to *10.18.128.51 zenwsimport*

*Localhost* should be *127.0.0.1*, as should all the rest if you want to block them.


```
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

[B]127.0.0.1[/B]  localhost

#start of lines added by WinHelp2002
# [Misc A - Z]
[B]127.0.0.1[/B]  fr.a2dfp.net
[B]127.0.0.1[/B]  m.fr.a2dfp.net
[B]127.0.0.1[/B]  ad.a8.net
[B]127.0.0.1[/B]  asy.a8ww.net
[B]127.0.0.1[/B]  abcstats.com
[B]127.0.0.1[/B]  a.abv.bg
[B]127.0.0.1[/B]  adserver.abv.bg
[B]127.0.0.1[/B]  adv.abv.bg
[B]127.0.0.1[/B]  bimg.abv.bg
[B]127.0.0.1[/B]  ca.abv.bg
```


----------



## Ent (Apr 11, 2009)

> *Localhost* should be *127.0.0.1*, as should all the rest if you want to block them.


I do want to block them. That's why I'm doing the testing on a copy.

As I said, my original hosts file which I'm still running under had them pointed to localhost. I replaced it with that IP because that's the IP that we want to be changed for the purposes of this thread. I also left a few copies of the localhost IP, and sure enough those aren't changed. The problem however is that the 10.17 entries *are *all changing to *10.18.128.51 zenwsimport*. Surely what we need here is something like the following



> # Start of entries inserted by Spybot - Search & Destroy
> 10.18.128.51 xxx.007guard.com
> 10.18.128.51 007guard.com
> 10.18.128.51 008i.com
> 10.18.128.51 xxx.008k.com


----------



## TheOutcaste (Aug 8, 2007)

Well, you wouldn't have sites you wanted to block pointing to the server, but it is possible that they have two or more names mapped to the same Server IP.

Good catch Ent, I hadn't thought of that possibility, was thinking only one address in the file that needed to be changed.:up::up:

So depends on if the OP wants to change all *10.17* addys to *10.18*, or only change the address for the *zenwsimport* entry. They may want some current names to remainn unchanged.

This will change only the *zenwsimport* entry, or add it if missing:

```
@Echo Off
SetLocal EnableDelayedExpansion
::PushD %SystemRoot%\System32\Drivers\Etc
PushD C:\Test
If Exist Hosts.new Del Hosts.new
Echo Reparsing IPs.
Set _Found=0
For /F "tokens=1* Delims= " %%A In (hosts) Do (
  Echo.%%A|Findstr /B "#">Nul
  If !Errorlevel!==0 (
    >>Hosts.new Echo.%%A %%B
  ) Else (
    If /I %%B==zenwsimport (
      >>Hosts.new Echo.10.18.128.51       %%B
      Set _Found=1
    ) Else (
      >>Hosts.new Echo.%%A       %%B
    )
  )
)
If %_Found%==0 >>Hosts.new Echo.10.18.128.51       zenwsimport
Set _Date=%date%%time%
Set _Date=%_Date: =%
Set _Date=%_Date:/=-%
Set _Date=%_Date::=-%
Rename Hosts %_Date%Hosts.old
Rename Hosts.new Hosts

Echo Reparse Complete.
Pause
PopD
```
This will change all *10.17* addys to *10.18*, and add the *zenwsimport* entry if missing:

```
@Echo Off
SetLocal EnableDelayedExpansion
::PushD %SystemRoot%\System32\Drivers\Etc
PushD C:\Test
If Exist Hosts.new Del Hosts.new
Echo Reparsing IPs.
Set _Found=0
For /F "tokens=1* Delims= " %%A In (hosts) Do (
  Echo.%%A|Findstr /B "#">Nul
  If !Errorlevel!==0 (
    >>Hosts.new Echo.%%A %%B
  ) Else (
    If %%A==10.17.128.51 (
      >>Hosts.new Echo.10.18.128.51       %%B
      If %%B==zenwsimport Set _Found=1
    ) Else (
      If %%B==zenwsimport (
        Set _Found=1
        >>Hosts.new Echo.10.18.128.51       %%B
      ) Else (
        >>Hosts.new Echo.%%A       %%B
      )
    )
  )
)
If %_Found%==0 >>Hosts.new Echo.10.18.128.51       zenwsimport
Set _Date=%date%%time%
Set _Date=%_Date: =%
Set _Date=%_Date:/=-%
Set _Date=%_Date::=-%
Rename Hosts %_Date%Hosts.old
Rename Hosts.new Hosts

Echo Reparse Complete.
Pause
PopD
```


----------



## Ent (Apr 11, 2009)

Re-reading the first post I think you're probably right. I assumed that he wanted to change a lot of entries from one specified IP to another specified IP and it didn't occur to me that there might be only one entry. Anyway, there's nothing more to be done until the OP comes back.


----------



## Squashman (Apr 4, 2003)

But like I said earlier, I believe they have something misconfigured with their Zenworks server if they have to force this with a hosts file.


----------

