3

I have a Windows batch file utilized in my Visual Studio tool chain that creates a list of files in a particular directory, and then uses "findstr" to narrow this list down to only the files whose names contain a particular string; and then does some work on these files.

dir /b \mypath\*.wav >wavRawList.txt

findstr /b /v "DesiredString" wavRawList.txt >wavListWithDesiredString.txt

for /f %%a in (wavListWithDesiredString.txt) do (

  [... do some stuff ...]

)

Visual Studio frequently reports errors from this batch file, and I think it's because wavListWithDesiredString.txt frequently ends up being a file with a length of 0. Is there a variety of "if exist wavListWithDesiredString.txt" where instead of "exist" I can substitute a command meaning "if it exists and its file length is greater than 0"?

Devin Burke
  • 13,642
  • 12
  • 55
  • 82
Bill
  • 31
  • 1
  • 2

3 Answers3

7

The more-or-less inline way, using for:

for %%x in (wavListWithDesiredString.txt) do if not %%~zx==0 (
    ...
)

or you can use a subroutine:

:size
set SIZE=%~z1
goto :eof

which you can call like this:

call :size wavListWithDesiredString.txt
if not %SIZE%==0 ...
Joey
  • 344,408
  • 85
  • 689
  • 683
1
IF EXIST %1 IF %~z1 GTR 0 ECHO Both conditions are satisfied.

Does not work, because if file does not exist this part: "IF %~z1 GTR 0" resolves to "IF GTR 0" which is invalid command and results in:

0 was unexpected at this time.

Delayed expansion does not help either. To fix use this:

if exist %1 (
    echo "Ouput file exists, checking size"
    for %%x in (%1) do if not %%~zx==0 (
        echo "File exists, size is non zero"
        ... DO SOMETHING ...
    ) else (
        echo "Size is zero"
    )
) else (
    echo "There is no file"
)
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
John Auden
  • 23
  • 6
0

I was able to solve the file size part of the question with another stack overflow question found here. I would use nesting to simulate the AND operator like the example below:

IF EXIST %1 IF %~z1 GTR 0 ECHO Both conditions are satisfied.

The %1 is a parameter that must be passed into a batch file.

Community
  • 1
  • 1
Ryan Gates
  • 4,501
  • 6
  • 50
  • 90