【问题标题】:If exist with multiple wildcards如果存在多个通配符
【发布时间】:2019-03-11 14:52:10
【问题描述】:

这些是要求:

  • 指定通配符以签入变量。
  • 对于每个通配符,验证是否有文件。如果没有,请警告用户(只需 echo)。
  • 处理生成的文件。

我尝试过的(仅适用于 1 个通配符):

SET wildcard=a*.txt
cd c:\somedirectory
IF EXIST "%wildcard%" (
    REM PROCESS THE FILES
) ELSE (
    ECHO There are no files that match that wildcard, please review.
)

这显然只有在通配符唯一的情况下才有效。

我尝试过的:

SET wildcard=a*.txt b*.txt
cd c:\somedirectory
FOR %%A IN (%wildcard%) DO (
    ECHO %%A
)

这将打印与a*.txtb*.txt 匹配的文件。我不希望发生这种扩展。我需要实际的通配符值才能进入循环。

通过扩展,我无法告诉用户他的某些通配符没有文件。例如。有文件a*.txt,但没有文件b*.txt。我需要告诉用户。比如:

a*.txt:有文件。
b*.txt:没有文件,请查看。

类似的东西(这不起作用,只是我正在寻找的想法):

SET wildcard=a*.txt b*.txt c*.txt
cd c:\somedirectory

REM loop on the wildcards
FOR %%A IN (%wildcard%) DO (

    REM verify if there are files for that wildcard
    IF EXIST %%A (

        REM loop on the files from the specific wildcard
        FOR %%F IN (%%A) DO (
            REM PROCESS THE FILES
        )
    ) ELSE (
        ECHO This pattern %%A has no files associated
    )
)

基本上,我可以防止在IF 语句中扩展%wildcard% 中的值吗?


对于@double-beep 的评论:

  • 您对多个IF EXIST 语句的想法正是我想要的,但我不知道用户需要多少通配符。

    SET wildcard=a*.txt b*.txt [...]
    REM this would be ok
    IF EXIST a*.txt ( ... )
    IF EXIST b*.txt ( ... )
    [...]
    

但是,根据用户在通配符变量中输入的内容,我该如何灵活地做到这一点?我想过循环通配符的值,但 FOR 进行了扩展,这是我不想要的。

【问题讨论】:

  • 输入 for /? 并查看 /f
  • 在 cmets 中写起来太复杂了,但是像 if exist a*.txt if exist b*.txt if exist c*.txt 这样的东西,但是你需要多个 elses。否则,您可以在ECHO This pattern %%A has no files associated 之后添加goto 并转到自定义子例程。我仍然不确定:你是什么意思?只需检查是否存在许多通配符以及它们是否不做某事?这里有什么问题?
  • Never use :label nor :: label-like comment inside a command block enclosed in () parentheses,使用REM 而不是::。此外,使用SET wildcard=a*.txt b*.txt
  • 知道了 JosefZ,我会这样做,然后编辑问题。谢谢!
  • @double-beep:我在问题中添加了一些细节来解决您的if 声明想法。

标签: batch-file


【解决方案1】:

这段代码呢,使用call带参数,不解析通配符:

@echo off
set "WildCard=a*.txt b*.txt *.vi"

call :LOOP %WildCard%
rem ...
goto :EOF


:LOOP
    if "%~1"=="" goto :EOF
    if exist "%~1" echo There are files that match the pattern: "%~1"
    shift /0
    goto :LOOP

【讨论】:

  • 非常好!我没想过使用shift,这非常有效!我喜欢这个网站和这里的社区。谢谢!
猜你喜欢
  • 2019-01-26
  • 2018-08-12
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多