【问题标题】:Search file with wildcard path使用通配符路径搜索文件
【发布时间】:2017-01-28 16:10:13
【问题描述】:

我想编写一个脚本来提示用户输入文件路径并列出找到的所有文件。文件路径可以包含通配符。类似于this 的东西。但是它的批处理脚本版本。例如:

C:\Somewhere\user*\app\version-*.*\start.exe

文件的位置可能如下:

C:\Somewhere\user345\app\version-1.0\start.exe
C:\Somewhere\user898\app\version-1.2\start.exe
C:\Somewhere\user898\app\version-1.3\start.exe

我尝试使用FOR,但结果比预期的要困难得多,因为FOR 不支持路径中间的通配符。
有没有办法列出这些文件? (也许不使用for?)

【问题讨论】:

  • 您可能希望使您提供的示例更具体。您说的是列出找到的所有文件,但我可以在不查看您的计算机的情况下告诉您,它们都将被称为 start.exe。您提供的路径等是正确的,还是您只是为了回答而编造的,希望以后您自己更改它们?
  • 示例@Compo 的哪一部分?是的,我编的

标签: batch-file path


【解决方案1】:

我认为这种递归解决方案效果很好;您可以将其命名为 WCDIR.bat

@echo off
setlocal

if "%~1" neq "" set "next=%~1" & goto next
echo Show files selected by several wild-cards
echo/
echo WCDIR wildcardPath
echo/
echo Each folder in the path may contain wild-cards
echo the last part must be a file wild-card
goto :EOF

:next
for /F "tokens=1* delims=\" %%a in ("%next%") do set "this=%%a" & set "next=%%b"
if defined next (
   for /D %%a in ("%this::=:\%") do (
      setlocal
      cd /D "%%~a" 2>NUL
      if not errorlevel 1 call :next
      endlocal
   )
) else (
   for /F "delims=" %%a in ('dir /B /A:-D "%this%" 2^>NUL') do echo %%~Fa
)
exit /B

编辑:我修复了最后一个for /F 命令中的一个小错误。

例如,在我的 Windows 8.1 64 位计算机中WCDIR.bat C:\Windows\Sys*\find*.exe 命令的输出是:

C:\Windows\System32\find.exe
C:\Windows\System32\findstr.exe
C:\Windows\SysWOW64\find.exe
C:\Windows\SysWOW64\findstr.exe

【讨论】:

    【解决方案2】:

    您可以尝试使用命令Where /?

    WHERE 命令大致相当于 UNIX 的“which”命令。默认情况下,搜索是在当前目录和 PATH 中完成的。

        @echo off
        Where /R "%programfiles%" *winrar.exe
        pause
    

    @echo off
    :: Example d'input
    set UserInput=*drive*
    
    :: building the Pattern
    set cmd=%Userinput%.exe
    
    :: storage Where.exe command in a macro, the execution will be faster
    set whereCmd=where.exe /r c:\windows\ %cmd%
    
    :: execution of macro and output formatting
    for /f %%a in ('%whereCmd%') do echo %%~nxa --^> %%a
    pause
    

    【讨论】:

    • 这不起作用。 /R 开关中给出的路径不能包含通配符。
    • 我试过 where /R C:\Windows\Sys* find*.exe 并得到类似“错误:无效目录”的内容。 Windows 8.1 在这里。这个命令对你有用吗?
    • @Aacini where /R "C:\Windows\System32" *find*.exe 这个有效,这个也有效where /R "C:\Windows\System32" *f*d*.exe
    • 请问?本题是关于"Search file with wildcard path",也就是这里的问题是"FOR不支持通配符在路径的中间"(如问题描述所指定)。解决方案应该找到具有如下路径的文件:C:\Windows\Sys*\find.exe...
    • ...(就像这个问题中的第一个例子:C:\Somewhere\user*\app\version-*.*\start.exe
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2016-12-19
    相关资源
    最近更新 更多