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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11225581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:38:16  来源:igfitidea点击:

How to check if a file is not empty in Batch

windowsbatch-file

提问by laggingreflex

There are several ways google throws at me for checking if a file is empty but I need to do the opposite.

谷歌向我抛出了几种方法来检查文件是否为空,但我需要做相反的事情。

If (file is NOT empty)

do things

How would I do this in batch?

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

回答by Bali C

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

回答by risingDarkness

this should work:

这应该有效:

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

help ifsays that you can add the NOTdirectly after the ifto invert the compare statement

help if说你可以在NOT后面直接添加if来反转比较语句

回答by David Brabant

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

Type help forin a command line to have explanations about the ~zA part

键入help for的命令行有关于〜ZA部分解释

回答by Hashbrown

You can leverage subroutines/external batch files to get to useful parameter modifierswhich solve this exact problem

您可以利用子例程/外部批处理文件来获得有用的参数修饰符来解决这个确切的问题

@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)


Alternatively

或者

notEmpty.bat

notEmpty.bat

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

yourScript.bat

yourScript.bat

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