如何在循环中处理 space 分隔文件类型模式的列表?

How to process a list of space separated file type patterns in a loop?

所以我正在制作一个批处理文件来对一些旧计算机进行一些备份,并且很难打印我试图备份到 cmd 提示符的文件类型,因为每当我 运行 这会将文本“*.png”更改为 "myfile.png"。所以它的功能就像一个通配符,即使我只是想打印“*.png”

这是我的代码:

echo off
cls
set "SelectedFileTypes=*.pdf *.docx *.tif *.txt *.png *.xcf *.jpeg *.raw *.jpg *.mp3 *.mp4 *.m4a *.wmv *.msdvd *.itdb"
echo %SelectedFileTypes%
echo/
for %%I in (%SelectedFileTypes%) do echo %%I
pause

这是我想要的输出:

*.pdf *.docx *.tif *.txt *.png *.xcf *.jpeg *.raw *.jpg *.mp3 *.mp4 *.m4a *.wmv *.msdvd *.itdb

*.pdf
*.docx
*.tif
*.txt
*.png
*.xcf
*.jpeg
*.raw
*.jpg
*.mp3
*.mp4
*.m4a
*.wmv
*.msdvd
*.itdb

这是我大部分时间得到的输出,它似乎是我所在目录中匹配的所有文件。

*.pdf *.docx *.tif *.txt *.png *.xcf *.jpeg *.raw *.jpg *.mp3 *.mp4 *.m4a *.wmv *.msdvd *.itdb

A+Study.pdf
after.txt
before.txt
story of my life.txt
TshirtIdea.txt
bananaForScale.png
windows_logo.png
BadTree.xcf
7ed48ccf-5746-4c86-b5c4-8c02ba0ccbf9.jpg

批处理代码的输出是正确的,因为命令 FOR 没有选项 /F 解释文件名模式列表,如命令 DIR 和 returns 匹配任何指定模式的所有文件名。

这里是一个示例,说明如何按照您的需要循环处理文件名模式列表。

@echo off
cls
setlocal EnableDelayedExpansion

rem Define the file type patterns in a single space separated list.
set "SelectedFileTypes=*.pdf *.docx *.tif *.txt *.png *.xcf *.jpeg *.raw *.jpg *.mp3 *.mp4 *.m4a *.wmv *.msdvd *.itdb"

rem Append a space at end if there is not already a space at end.
if not "%SelectedFileTypes:~-1%" == " " set "SelectedFileTypes=%SelectedFileTypes% "

rem This loop is executed until all file type patterns are processed
rem determined by an empty string for the remaining file type patterns.
rem The FOR command returns the first pattern of the space separated
rem patterns and the string substitution removes this pattern and the
rem following space from the list of file name patterns.

:NextFileType
if "%SelectedFileTypes%" == "" goto Finished
for /F "tokens=1" %%# in ("%SelectedFileTypes%") do (
    set "FileType=%%#"
    set "SelectedFileTypes=!SelectedFileTypes:%%# =!"
)

rem Do here whatever should be done with this file type pattern.
echo File type is: %FileType%
goto NextFileType

:Finished
echo Processed all file types.
endlocal
pause

要了解使用的命令及其工作原理,请打开命令提示符 window,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • cls /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • rem /?
  • set /?
  • setlocal /?

对于其他解决方案,请查看 运行 以 [batch-file] split string 作为搜索词的 Stack Overflow 搜索返回的列表。

您可以使用带有 call 的子例程,并将 SelectedFileTypes 的值作为参数传递给它。与 shiftifgoto 一起,您可以创建一个条件循环,returns SelectedFileTypes 的每个项目:

@echo off
cls
set "SelectedFileTypes=*.pdf *.docx *.tif *.txt *.png *.xcf *.jpeg *.raw *.jpg *.mp3 *.mp4 *.m4a *.wmv *.msdvd *.itdb"
echo(%SelectedFileTypes%
echo(
call :SUB %SelectedFileTypes%
pause
exit /B

:SUB
shift
if "%~0"=="" goto :EOF
echo(%~0
goto :SUB

这种方法的最大优点是您不必自己进行解析,而让命令解释器进行解析,支持标准分隔符SPACE, TAB, ,, ;=.