如何批量选择基于文件扩展名的多个操作之一

时间:2014-11-29 02:34:54

标签: batch-file multiple-conditions

我是使用FOR命令的业余爱好者。我需要一个批处理文件,它将根据文件的扩展名运行5个文件转换工具之一。我想将文件放到批处理文件图标上并将其转换。

由于我的列表很大,我不能使用嵌套的IF。

到目前为止我尝试过:

@ECHO OFF

SET cadfile=.dwg .dxf .dwf
SET gsfile=.ps .eps .epi .epsp
SET xxxxxx=.xx .xx and goes on

FOR %%~x1 in (%cadfile%) do (
    Do some action
FOR %%~x1 in (%gsfile%) do (
    Do some other action
)
)

%% ~x1变量用于文件的文件扩展名,该文件扩展名在批处理文件上拖放。 (编辑更清楚)

3 个答案:

答案 0 :(得分:0)

我认为这对你有用。它会在单个For循环中查看所有扩展组,并在找到匹配的扩展名时调用标签,您可以在其中执行转换和任何相关任务。您需要完成“groupN”变量和标签。

@echo off
SETLOCAL EnableDelayedExpansion

    set file="%1"
    set ext=%~x1

    :: Set the 5 groups of extensions that have different converters
    set group1=.dwg, .dxf, .dwf
    set group2=.ps, .eps, .epi, .epsp

    For %%A in (1 2 3 4 5) do (
        set groupnum=group%%A
        call set thisgroup=%%!groupnum!%%
                :: Look for extension in this group
                echo.!thisgroup!|findstr /i /C:"%ext%" >nul 2>&1
                    if not errorlevel 1 call :group%%A
                    :: else go loop next group
    )
    echo Extension not found in any group &pause &goto end

:group1
    echo group1 file to convert is %file%
    goto end
:group2
    echo group2 file to convert is %file%
    goto end

:end
pause
exit

答案 1 :(得分:0)

FOR %%a in (%cadfile%) do (
    if /i "%~x1"=="%%a" some_action "%~1"
)

...并按照其他实用程序/列表的弹跳球

答案 2 :(得分:0)

以下方法可让您轻松添加和修改扩展程序/应用程序列表。请注意,您只需要编辑第一个FOR命令中的值;程序的其余部分是您不需要关心的解决方案......

@echo off
setlocal EnableDelayedExpansion

rem Define the list of extensions per application:
rem (this is the only part that you must edit)
for %%a in ("cadfile=.dwg .dxf .dwf"
            "gsfile=.ps .eps .epi .epsp"
            "xxxxxx=.xx .xx1 .xx2") do (

   rem The rest of the code is commented just to be clear,
   rem but you may omit the reading of this part if you wish

   rem Separate application from its extensions
   rem and create a vector called "ext" with an element for each pair
   for /F "tokens=1,2 delims==" %%b in (%%a) do (
      rem For example: %%b=cadfile, %%c=.dwg .dxf .dwf
      for %%d in (%%c) do set "ext[%%d]=%%b"
      rem For example: set "ext[.dwg]=cadfile", set "ext[.dxf]=cadfile", set "ext[.dwf]=cadfile"
      rem In the next line: set "ext[.ps]=gsfile", set "ext[.eps]=gsfile", etc...
   )
)

rem Now process the extension of the file given in the parameter:
if defined ext[%~x1] goto !ext[%~x1]!
echo There is no registered conversion tool for %~x1 extension
goto :EOF

:cadfile
echo Execute cadfile on %1 file
rem cadfile %1
goto :EOF

:gsfile
echo Execute gsfile on %1 file
rem gsfile %1
goto :EOF

etc...

如果每个转换工具都以相同的方式执行,并且不需要其他参数(只是文件名),那么您可以省略各个部分并直接以这种方式执行转换工具:

if defined ext[%~x1] !ext[%~x1]! %1

有关数组概念的进一步说明,请参阅this post