Windows批处理文件如何检测文件是否为> 0个字节?

时间:2010-06-14 21:02:17

标签: batch-file

我的Visual Studio工具链中使用了一个Windows批处理文件,它在特定目录中创建了一个文件列表,然后使用“findstr”将此列表缩小到只包含名称包含特定字符串的文件;然后对这些文件进行一些处理。

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经常报告此批处理文件中的错误,我认为这是因为wavListWithDesiredString.txt经常最终成为长度为0的文件。是否存在各种“if exists wavListWithDesiredString.txt”而不是“存在” “我可以替换一个命令,意思是”如果它存在且文件长度大于0“?

3 个答案:

答案 0 :(得分:5)

或多或少的内联方式,使用for

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

或者您可以使用子程序:

:size
set SIZE=%~z1
goto :eof

你可以像这样打电话:

call :size wavListWithDesiredString.txt
if not %SIZE%==0 ...

答案 1 :(得分:0)

我能够使用another stack overflow question found here解决问题的文件大小部分。我会使用嵌套来模拟AND运算符,如下例所示:

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

%1是必须传递到批处理文件的参数。

答案 2 :(得分:0)

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

不起作用,因为如果文件不存在这部分: “IF%~z1 GTR 0”解析为“IF GTR 0”,这是无效命令并导致:

0 was unexpected at this time.

延迟扩张也无济于事。要解决这个问题:

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"
)
相关问题