windows 批处理文件:检查是否存在具有模式的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34202512/
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-08 19:23:14  来源:igfitidea点击:

Batch-file: Check if file with pattern exist

windowsbatch-filefiltercmdpath

提问by vasilenicusor

I have a strange situation and I don't know what is wrong

我有一个奇怪的情况,我不知道出了什么问题

I need to check if in a directory exist at least one file with a pattern.

我需要检查目录中是否至少存在一个具有模式的文件。

IF EXIST d:\*Backup*.* (
   ECHO "file exist"
) ELSE (
   ECHO "file not exist"
)

If on d:\ I have a file x_Backup.txtand a folder BackupI get file existbut if i have only folder BackupI get again file exist, seems that the dot from path is ignored.

如果d:\我有一个文件x_Backup.txt和文件夹Backup,我得到file exist,但如果我只有文件夹Backup我爬不起来file exist,似乎从路径点被忽略。

回答by Squashman

There are undocumented wildcards that you can use to achieve this as well.

您也可以使用未记录的通配符来实现此目的。

IF EXIST "D:\*Backup*.<" (
   ECHO "file exist"
) ELSE (
   ECHO "file not exist"
)

This wildcard option and other were discussed in length at the following two links. http://www.dostips.com/forum/viewtopic.php?t=6207

在以下两个链接中详细讨论了此通配符选项和其他选项。 http://www.dostips.com/forum/viewtopic.php?t=6207

http://www.dostips.com/forum/viewtopic.php?f=3&t=5057

http://www.dostips.com/forum/viewtopic.php?f=3&t=5057

From those links:

从这些链接:

The following wildcard characters can be used in the pattern string.

Wildcard character  Meaning

* (asterisk)
Matches zero or more characters

? (question mark)
Matches a single character

" 
Matches either a period or zero characters beyond the name string

>
Matches any single character or, upon encountering a period or end of name string, advances the expression to the end of the set of contiguous >

<
Matches zero or more characters until encountering and matching the final . in the name

回答by Aacini

Use this; it works with any specific pattern:

用这个; 它适用于任何特定模式:

set "fileExist="
for %%a in (d:\*Backup*.*) do set "fileExist=1" & goto continue
:continue
IF DEFINED fileExist (
   ECHO "file exist"
) ELSE (
   ECHO "file not exist"
)

回答by foxidrive

This is another alternative.

这是另一种选择。

dir d:\*back*.* /b /a-d >nul 2>&1
if errorlevel 1 echo files exist

回答by user326608

*.*is equivalent to *in dos. It just means 'anything', not anything-period-anything.

*.*相当于*在 dos 中。它只是意味着“任何东西”,而不是任何东西-时期-任何东西。

To check for the directory, try this:

要检查目录,请尝试以下操作:

IF EXIST D:\*Backup*\ (
   ECHO "directory exist"
) ELSE (
   ECHO "directory not exist"
)