【问题标题】:Batch File: Take parameters from n-th index to the last index批处理文件:从第 n 个索引到最后一个索引取参数
【发布时间】:2015-01-16 16:06:08
【问题描述】:

我有无限的参数列表 a b c d e f g h.... 我想在批处理文件中运行如下命令:

mybatchfile a b c d e f g h I j k l m n ...

我有一个程序,我想将参数从 d 带到最后。我能做到吗? 我知道 %* 将采用所有参数。我可以通过这种方式排除一些参数吗?

【问题讨论】:

  • 在批处理中使用 shift 命令 3 次,然后 %1 将匹配您的 d 参数。请参阅此处的示例:ss64.com/nt/shift.html
  • 但是如何走到最后。如果我在 3 次 SHIFT 后使用 %*,我也会得到完整的列表参数。
  • 使用与您必须处理的参数数量一样多的移位命令。如果您不知道数字,请使用 shift until %1=""
  • 你也可以使用 shift /n :从第 n 个参数开始,其中 n 可能介于 0 和 8 之间。见stackoverflow.com/a/21546753/381149
  • 你能解释清楚吗?例如,我的列表参数是 a b c d e f g h I j k l m n(14 个参数)。我想从 d 到 n。不使用 %5 %6 %7.... 怎么写?我是批处理文件的新手:(

标签: batch-file command-line


【解决方案1】:

你的批次:

@echo off
rem remove 3 first args
SHIFT 
SHIFT
SHIFT

:start
if "%1"=="" (goto :exit)
:: Do whatever with token %1
Echo [%1] 
:: Shift %2 into %1 
SHIFT
goto :start

:exit
::pause

将输出:

C:\temp>shift.bat a b c d e f g h i j k l m n
[d]
[e]
[f]
[g]
[h]
[i]
[j]
[k]
[l]
[m]
[n]

【讨论】:

  • 是的,这段代码帮助我们将参数从 d 到 n。你能告诉我如何召唤我的命令吗?我需要一个新列表才能调用看起来像 myprogram list_new_param?
【解决方案2】:
@echo off
setlocal

:: Preserve first 3 arguments so they may be used elsewhere in the script, if needed.
set arg1=%1
set arg2=%2
set arg3=%3

:: Now build the argument list for the remaining arguments
shift /1
shift /1
shift /1
set "args="
:getArgs
if "%~1" neq "" (
  set args=%args% %1
  shift
  goto :getArgs
)

:: Call your program
yourProgram %args%

:: Carry on with the rest of your script, as needed

如果你的程序是另一个批处理脚本,别忘了使用call yourProgram %args%,否则它不会返回。

【讨论】:

    【解决方案3】:
    @echo off
    for /f "tokens=1-3,* delims= " %%a in ("%*") do set "params=%%d"
    echo here are the parameters 4...n:
    echo %params%
    start myprogram %params%
    

    【讨论】:

    • @user3733276 - 如果任何跳过的参数包含空格,这将失败。例如,如果%* = "partA partB" "arg2" "arg3" "arg4" "arg5",那么它将产生"arg3" "arg4" "arg5"。正确的输出是"arg4" "arg5"
    • @user3733276 - 如果任何参数包含引用的特殊字符(如 &|),也会出现问题。
    猜你喜欢
    • 2013-09-14
    • 2016-05-16
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多