如果文件是空的,使用Windows批处理文件如何检测(和删除)? [英] How do I Detect (and Delete) a File if it is Empty using a Windows Batch File?
问题描述
如何使用Windows批处理文件检测文件是否为空?我想删除错误日志,如果它们是空的。
我知道for循环解决方案,如 http://anderwald.info/scripting/windows-batch-delete-all-empty-files-in -a-specified-folder / ,但是我想知道如果你知道有问题的特定单个文件需要测试,如果有一个更优雅的解决方案,因为我不想删除其他零字节文件
您引用的链接使用以下内容删除所有0个长度的文件
for / Fdelims =%Iin('dir / B')do if not exist%I \if%〜zI EQU 0 del %I
这更复杂,效率不高。简单地使用:
for%F in(*)do if%〜zF equ 0 del%F
如果特定文件为零长度,则要删除该文件。因此,只需用您的文件名替换 *
通配符。
%F in(yourFileName)如果%〜zF equ 0 del%F
你将在批处理文件中使用它,而不是需要将所有百分比加倍( %% F
, %%〜zF
)
如果不想使用FOR循环,可以使用CALL参数 - 它使用与FOR变量相同的修饰符。但是,CALL比FOR慢(在您的情况下可能不重要)
@echo off
call:deleteIfEmpty yourFileName
exit / b
:deleteIfEmpty
如果%〜z1 eq 0 del%1
exit / b
编辑
我想到了另一种方式。
^
的FINDSTR搜索字符串将匹配文件的所有行。但是一个空文件没有任何行。因此,如果FINDSTR无法匹配某行,只需删除该文件。> nul findstr^YourFileName|| delyourFileName
How do I detect if a file is empty using a Windows batch file? I want to delete error logs if they are empty.
I am aware for for loop solutions such as http://anderwald.info/scripting/windows-batch-delete-all-empty-files-in-a-specified-folder/ but I was wondering if there was a more elegant solution if you know the specific single file in question that needs to be tested, as I may not wish to delete other zero byte files in the folder.
解决方案The link you cited used the following to delete all 0 length files
for /F "delims=" "%I" in ('dir /B') do if not exist "%I\" if %~zI EQU 0 del "%I"
That is more complicated and not as efficient as it could be. It is much simpler to simply use:
for %F in (*) do if %~zF equ 0 del "%F"
You want to delete a specific file if it is zero length. So just substitute your file name for the
*
wild card.for %F in ("yourFileName") do if %~zF equ 0 del "%F"
If you are going to use this in a batch file than you need to double all the percents (
%%F
,%%~zF
)If you don't want to use a FOR loop, you can use a CALL parameter instead - it uses the same modifiers as FOR variables. However, CALL is slower than FOR (probably not significant in your case)
@echo off call :deleteIfEmpty "yourFileName" exit /b :deleteIfEmpty if %~z1 eq 0 del %1 exit /b
EDIT
I've thought of yet another way. A FINDSTR search string of
"^"
will match all lines of a file. But an empty file doesn't have any lines. So simply delete the file if FINDSTR fails to match a line.>nul findstr "^" "yourFileName" || del "yourFileName"
这篇关于如果文件是空的,使用Windows批处理文件如何检测(和删除)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!