如何检查cmd批处理脚本中是否存在具有特定模式的文件名?
如何在 if exit
语句中使用 [0-9]
。我想检查第二个数字是1-9的文件是否存在。
If exist "filepath\\a[1-9]*" (echo "yes")
看来 [1-9]
通配符在 if exit
语句中不起作用。
您知道如何实施这项检查吗?
例如 当名为 a1 (a2da) 的文件存在但不存在 a0 (a0ss) 时打印“yes”
How to use [0-9]
in if exist
statement. I want to check a file with second digit is 1-9 exist or not.
If exist "filepath\\a[1-9]*" (echo "yes")
It seems [1-9]
wildcard does not work in if exist
statement.
Do you have any idea how to implement this check?
e.g.
print "yes" when a file named a1 (a2da) exists, but not a0 (a0ss)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于这是一个批处理文件,并且只写入一次,因此几乎不需要尝试使命令尽可能短。因此,只需使用一个
dir
命令和一个echo
命令,而不是当前接受的答案,该答案实际上运行十个if
命令,可能是九个set
命令和一个echo
命令。由于
filepath
是恒定的,您甚至可以这样做:但是请注意,您的问题不够清晰,无法确定您的完整任务。如果
a[123456789]...
存在于filepath
中,此示例将打印Yes
,无论名为a0 的文件是否存在,它都会执行此操作...
也存在于filepath
中。As this is a batch file, and is only written once, there's little need to try to make your command as short as possible. Therefore just use one
dir
command and oneecho
command, instead of the currently accepted answer which essentially runs tenif
commands, potentially nineset
commands, and oneecho
command.As
filepath
is constant, you could even do it like this:Please note however, that your question is not clear enough to determine your full task. This example will print
Yes
ifa[123456789]…
exists infilepath
, it will do that regardless of whether a file nameda0…
also exists infilepath
.cmd
中唯一支持 REGEX(残缺版本)的命令是findstr
。因此,您可以使用它来完成您的任务:注意,这还会找到诸如
a12anything.txt
和A2anything.txt
之类的文件,但不会找到a0anything.txt
>。The one and only command in
cmd
that supports (a crippled version of) REGEX isfindstr
. So you can use that to complete your task:Note, this will also find files like
a12anything.txt
andA2anything.txt
but nota0anything.txt
.如果您只检查第二个字符,而不考虑其后的其他字符,则可以使用如下内容:
If you only check the second character, without considering the other characters after it, you can use something like this:
另一种方法是使用 PowerShell。如果您使用的是受支持的 Windows 系统,则它已安装。
Another way to do this would be to use PowerShell. If you are on a supported Windows system it is already installed.