M. Stephen
M. Stephen

Reputation: 65

Using findstr in if in batch-file

I tried last week to figure out how an if works in a batch file and no that it should work it just doesn't. I have no idea what's wrong or how to solve the problem since I may have made an error with the if or that I'm missing out on something important.

findstr /C:"Firefox" C:\TestIffile.txt
pause
IF (findstr /C:"Firefox" C:\TestIffile.txt) (
ECHO Firefox > C:\TestIffileResult.txt
) ELSE (
ECHO no Firfox
)

The first findstr works fine and gives me this result. DisplayName REG_SZ Mozilla Firefox 58.0.2 (x64 en-GB) which is perfectly fine. The second findstr gives me something like "Firefox was unintended". I've been told that the if would handle the findstr command with a true or false signal but if so why won't it work properly? Thank you in advance.

Btw it's not to find the exe of the program but to save a lot of work by filtering out unwanted lines in my datafiles.

Upvotes: 0

Views: 8582

Answers (1)

Compo
Compo

Reputation: 38579

Without changing your provided search term, this is how I'd structure it using Find:

(Find /I "Firefox"<"C:\TestIfFile.txt" >Nul && (Echo Firefox
) || Echo No Firefox)> C:\TestIffileResult.txt

…and using FindStr:

(FindStr /IC:"Firefox" "C:\TestIfFile.txt" >Nul && (Echo Firefox
) || Echo No Firefox)> C:\TestIffileResult.txt

In either case I would probably first put in a condition based on the existence or otherwise of C:\TestIfFile.txt.

@Echo Off
If Not Exist "C:\TestIfFile.txt" Exit /B

I would also note that most Windows systems by default prevent writing to a file in the root of the system drive, without administrative privileges.

Upvotes: 2

Related Questions