如何在批处理中检查文件是否为空

时间:2012-06-27 11:53:43

标签: windows batch-file

谷歌有几种方法可以检查文件是否为空,但我需要做相反的事情。

If (file is NOT empty)

do things

我将如何批量执行此操作?

4 个答案:

答案 0 :(得分:20)

for /f %%i in ("file.txt") do set size=%%~zi
if %size% gtr 0 echo Not empty

答案 1 :(得分:8)

这应该有效:

for %%R in (test.dat) do if not %%~zR lss 1 echo not empty

help if表示您可以在NOT之后直接添加if以反转比较语句

答案 2 :(得分:5)

set "filter=*.txt"
for %%A in (%filter%) do if %%~zA==0 echo."%%A" is empty

在命令行中键入help for以获得有关~zA部分的说明

答案 3 :(得分:2)

您可以利用子程序/外部批处理文件来获得解决此问题的有用parameter modifiers

@Echo OFF
(Call :notEmpty file.txt && (
    Echo the file is not empty
)) || (
    Echo the file is empty
)
::exit script, you can `goto :eof` if you prefer that
Exit /B


::subroutine
:notEmpty
If %~z1 EQU 0 (Exit /B 1) Else (Exit /B 0)

可选地

notEmpty.bat

@Echo OFF
If %~z1 EQU 0 (Exit /B 1) Else (Exit /B 0)

yourScript.bat

Call notEmpty.bat file.txt
If %errorlevel% EQU 0 (
    Echo the file is not empty
) Else (
    Echo the file is empty
)