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

时间:2016-04-28 00:58:14

标签: batch-file windows-scripting

所以我正在创建一个批处理文件来对一些旧计算机进行一些备份,并且很难打印我正在尝试备份到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

2 个答案:

答案 0 :(得分:1)

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

以下是如何在循环中处理文件名模式列表的一个示例。

@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

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

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

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

答案 1 :(得分:1)

您可以使用call的子例程,并将SelectedFileTypes的值作为参数传递给它。与shiftifgoto一起,您可以创建一个条件循环,它返回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 ,;=