Question

I have the following line in a batch script

for %%a in (*.rmt) do (findstr /C:"        model='" %%a)>tmp.par

When I run this on an empty folder, the errorlevel is still 0.

However, if I replace *.rmt with a filename, say x.rmt, which doesnt exist in the folder either, the errorlevel becomes 1.

Ideally, if there are no RMT files in the folder, shouldnt the errorlevel!=0?

I require this For loop to work on *.rmt, as there might be 0 to multiple RMT files in a folder. Please help.

Thanks.

Note: If the string " model='" exists in one RMT file, it will compulsorily be present in all the other RMT files(if any) in the folder.

Was it helpful?

Solution

The findstr is never executed if there are no matches to the *.rmt, hence the errorlevel remains unchanged.

When you use x.rmt, FOR changes behaviour - it's no longer looking for a filename matching, it's looking at a particular string - which may or may not be a filename, which may or may not exist.

You could deliberately set errorlevel before the for

@ECHO OFF
SETLOCAL
ECHO y|FIND "x">nul
for %%a in (*.rmt) do (findstr /C:"        model='" %%a)
ECHO errorlevel=%errorlevel%
GOTO :EOF

which will return errorlevel 1 unless the match is found.

OTHER TIPS

Try this:

@echo off
for /F "delims=" %%i in ('dir /b "path_to_dir\*.rmt"') do (
   :: echo Folder is NON empty
   findstr /C:"model='" %%i >> C:\testlog.log
   goto :EOF
)

No, the FOR command never sets the ERRORLEVEL <> 0 if there are no iterations.

Yes, the following command reports ERRORLEVEL=1:

for %%a in (notExists.rmt) do (findstr /C:"        model='" %%a)>tmp.par

But that is because the simple FOR simply lists the string(s) within the IN() clause if they do not contain wildcards. It doesn't bother checking to see if the file exists. So your FINDSTR command is actually raising the error because it cannot find the file, not the FOR statement.

Your command is flawed in that each iteration overwrites the previous tmp.par. That can be easily fixed by adding an extra level of parentheses. This also will create an empty tmp.par if no files were found or if none of the files contained the search string. The ERRORLEVEL cannot be relied upon because its value will not have been set if no files were found, or it may be 0 or 1 depending on if the last file contained the search string.

(for %%a in (*.rmt) do (findstr /C:"        model='" %%a))>tmp.par

If you don't mind having a filename: prefix on each line of output, then you can simplify your code to:

findstr /C:"        model='" *.rmt >tmp.par 2>nul

This also will create an empty tmp.par file if no files were found, or if none of the files contain the search string. But now the ERRORLEVEL will be reliable. The ERRORLEVEL is 1 if no files are found or if no files contain the search string. Otherwise the ERRORLEVEL will be 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top