0

%params%包含一组可变的参数:

/tidy /log /truncate /convert D:\libdir 或者可能

/log /tidy D:\cyclea\libfolder /test /convert /truncate

对于除(当前单个)文件路径元素之外的所有内容,我都使用它:

 if "%params%"=="%params:log=%" goto :DontLogit

   if NOT "%params%"=="%params:/tidy=%" (call tidysub: & do something else )

现在我想提取文件路径元素并将其用作命令的参数,例如chdir

我玩过,但我对 CMD 字符串操作和for循环很弱。

我想保持参数的顺序可变。信息来自这里:

   FOR %%s IN (%*) DO (set params=!params! %%s)
4

2 回答 2

1
@ECHO OFF
SETLOCAL
SET swparams=log tidy test convert truncate
FOR %%i IN (%swparams% other) DO SET "%%i="
FOR %%i IN (%*) DO (
  SET "used="
  FOR %%p IN (%swparams%) DO (IF /i "/%%p"=="%%~i" SET %%p=Y&SET used=Y)
  IF NOT DEFINED used CALL SET other=%%other%% "%%~i"
  )

ECHO =============paramsreport===========
FOR %%i IN (%swparams%) DO IF DEFINED %%i (ECHO %%i:set) ELSE (ECHO %%i:clear)
ECHO other=%other%
FOR %%i IN (%other%) DO ECHO %%i or %%~i
GOTO :EOF 

Here's a way that should be extensible for you.

Simply set you switch-parameters into the list in swparams.

the parameter-names and OTHER are set to [nothing] to ensure they're not already set in the environment. Ech supplied parameter is applied to %%i in turn, and matched against each defined swparam in turn. the variable USED is cleared before the match and if the match (of /switchparametername is found, the switch parameter is set and the USED flag is set. if the used flag is not set gainst any of the switch parameters, then a parsing trick is used to accumulate any unrecognised strings into OTHER

The "%%~i" mechanism first dequotes the item in %%i, then quotes it. In this way, it ends up quoted, regardless of whether it originally has quotes or not.

The /i on the if performs a case-insensitive match.

hence running this batch

thisbatch /tidy "C:\some filename with spaces.txt"

will yield TIDY set to Y, LOG,test, convert, truncate not set and other set to "C:\some filename with spaces.txt"

于 2013-04-14T03:06:18.470 回答
0
@echo off
setlocal EnableDelayedExpansion

rem Get the single filepath element (with colon in second character):
set params=/tidy /log /truncate /convert D:\libdir
set filepath=
for %%a in (%params%) do (
   set par=%%a
   if "!par:~1,1!" == ":" (
      set filepath=%%a
   )
)
if defined filepath (
   echo Filepath = %filepath%
) else (
   echo Filepath not given
)
echo/

rem Get multiple filepath elements in an *array*:
set params=/log /tidy D:\cyclea\libfolder /test /convert D:\libdir /truncate
set i=0
for %%a in (%params%) do (
   set par=%%a
   if "!par:~1,1!" == ":" (
      set /A i+=1
      set filepath[!i!]=%%a
   )
)
echo There are %i% filepath elements:
for /L %%i in (1,1,%i%) do (
   echo %%i- !filepath[%%i]!
)

您可以在这篇文章中查看有关数组管理的进一步描述:cmd.exe (batch) 脚本中的数组、链表和其他数据结构

于 2013-04-14T04:59:01.937 回答