Batch Question help with Findstr

Dell
December 11, 2007 at 10:10:41
Specs: Window 2000, 512

I want to create a scenario by which I can query a text file (test123.txt) for a specific string (userstat=1). If the search is successful, then "search successful" will be printed on the screen. Otherwise it should print that the search failed. I am writing my first Batch program so if you could be fairly specific it would help me a lot. Thanks again.

See More: Batch Question help with Findstr

Report •


#1
December 11, 2007 at 11:41:55

The Windows Command Processor's language is quite powerful, albeit a bit quirky. So I'll try and keep it simple.

Type FINDSTR /? for full details of how to use FINDSTR.

The first line in your batch file should be:

@echo off

The @ character suppresses the echoing of the current command on that line, and the echo off command supresses all subsequent echoing. The echo command in fact has two seprate uses: one for controlling the echoing of commands in a batch file, and another for printing a line to the console. Well, I did say it's quirky.

(Advanced question: how do you print out a line that says "off", if the command "echo off" doesn't actually print "off"? Well, I won't answer here, except to say this demonstrates that it is indeed quirky.)

If you don't want FINDSTR to print the matching line in the file, use the Command Processor's redirection feature to send the output to the null device (which uses the special file name "nul"):

FINDSTR "userstat=1" test123.txt > nul

Now how do you know if the search was successful, if the output was not shown? The FINDSTR utility returns a zero exit code (called errorlevel) if it finds the search term, and non-zero (positive value) otherwise. So, our next line in the batch file is:

if errorlevel 1 (
echo Search successful
) else (
echo Search failed
)

Note that the "else" part MUST be on the same line as the closing bracket, as shown above. The language is very line-oriented, not free-form like C or Java. Type IF /? for full details of how to use the IF command. But simply put, the above test if the errorlevel is 1 or above.

Type "%windir%\Help\ntcmds.chm" at the command prompt for full details of how to use commands in batch files.


Report •

#2
December 11, 2007 at 13:38:03

klint: how do you print out a line that says "off", if the command "echo off" doesn't actually print "off"?
echo.off


Report •

#3
December 12, 2007 at 04:39:55

Hi klint,

errorlevel 1 is a 'not found'


=====================================
If at first you don't succeed, you're about average.

M2



Report •

Related Solutions

#4
December 12, 2007 at 06:57:12

Oops, thanks for that, what I meant to write was

if errorlevel 1 (
echo Search failed
) else (
echo Search successful
)



Report •


Ask Question