# CMD If find in file



## dropdeadcriminal (Nov 10, 2011)

Hello,
My CMD line code is very rusty. I need some help assembling some pieces. 
I want to search the hosts file, see if there is a line of code there, and if not add it. 
I know i need to:
find /c "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts
If the result of that is a 0 i need to:
if [%h%]==[0] echo 192.168.x.x intranet.com>>C:\WINDOWS\system32\drivers\etc\hosts
The part I cant recall is how to set the part of result of _find /c "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts_ with the count to _%h%_

Can anyone help.

Thanks


----------



## dropdeadcriminal (Nov 10, 2011)

never mind. I go it:

set nl=^& echo.
set chkhst=find /c "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts
FOR /f "tokens=3 delims= " %G IN ('%chkhst% ^|find ":"') DO set ipf=%G
if [%ipf%]==[0] echo %nl%>>C:\WINDOWS\system32\drivers\etc\hosts
if [%ipf%]==[0] echo 192.168.x.x intranet.com>>C:\WINDOWS\system32\drivers\etc\hosts


----------



## Squashman (Apr 4, 2003)

Are you say you wanted to check if the errorlevel equals Zero which means it found what you wanted in the file.


```
IF %errorlevel%=="0" echo I found it
```


----------



## Squashman (Apr 4, 2003)

You can actually do what you are trying to do with a single line of code.


```
find "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts ||echo 192.168.x.x intranet.com>>C:\WINDOWS\system32\drivers\etc\hosts
```


----------



## dropdeadcriminal (Nov 10, 2011)

Efficient!
Do you have a trick to throw a new line in before adding the text as well?


----------



## Squashman (Apr 4, 2003)

dropdeadcriminal said:


> Efficient!
> Do you have a trick to throw a new line in before adding the text as well?


With one line

```
find "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts ||echo.>>C:\WINDOWS\system32\drivers\etc\hosts &&echo 192.168.x.x intranet.com>>C:\WINDOWS\system32\drivers\etc\hosts
```
Using an IF statement to check the error level

```
find "192.168.x.x" C:\WINDOWS\system32\drivers\etc\hosts
IF NOT %errorlevel%=="0" (
     echo.>>C:\WINDOWS\system32\drivers\etc\hosts
     echo 192.168.x.x intranet.com>>C:\WINDOWS\system32\drivers\etc\hosts
)
```
Read this so you understand what the operators are doing.
http://judago.webs.com/batchoperators.htm


----------

