保存命令参数数组批 [英] Saving command arguments to array batch

查看:202
本文介绍了保存命令参数数组批的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来创建的批次接收参数数组。

I'm looking for a way to create an array of the arguments the batch receives.

例如:如果我运行 bfile.bat 1 2 3 4 5 我要的5个细胞 1,2,3数组,4,5

Example: If I run bfile.bat 1 2 3 4 5 I'll have an array with the 5 cells 1, 2, 3, 4, 5.

任何想法?

推荐答案

Windows批处理并没有真正包括阵列功能,在没有进行排序,长度等在其他语言中数组成员函数。 Aacini写了对此事彻底说明性

Windows batch scripting doesn't really include functionality for arrays, in that there are no array member functions for sorting, length, etc as in other languages. Aacini has written a thorough expository on the matter.

说到这里,你可以模拟阵列不够好,完成你的描述。

Having said that, you can simulate arrays well enough to accomplish what you describe.

@echo off
:: arr.bat -- simulates creation of an array with script arguments
setlocal enabledelayedexpansion

set args=%*
set arr.length=0

rem delayed expansion of %args% here to prevent if statement from freaking out
rem if quotation marks or spaces are encountered
if #!args!==# goto :usage

rem ###############
rem construct array
rem ###############

rem surround each argument with quotation marks and loop through them
rem 1 "2 3" 4 becomes "1" ""2" "3"" "4" (keeping 2 and 3 grouped)
for %%I in ("%args: =" "%") do (

    rem Pop quiz, hotshot.  Why did I not just use `set arr[!arr.length!]=%%~I`
    rem to strip the quotation marks?  Try it and see what happens.
    set val=%%I
    set arr[!arr.length!]=!val:"=!

    rem incrememt %array.length%
    set /a arr.length=!arr.length! + 1
)

rem ##############
rem retrieve array
rem ##############

echo arr[] has a length of %arr.length%.

rem arr.Ubound is the highest index in the array.  For instance, if the array
rem has 4 elements, then !arr[%arr.Ubound%]! refers to %arr[3]%.
set /a arr.Ubound=%arr.length% - 1
for /L %%I in (0, 1, %arr.Ubound%) do (

    rem To retrieve an array element, expand the inner variable immediately
    rem while delaying expansion of the outer variable.
    echo arr[%%I] = !arr[%%I]!
)

goto :EOF

:usage
echo Usage: %~nx0 [arg [arg [arg]]] etc.

下面是一些例子输出。

C:\Users\me\Desktop>arr
Usage: arr.bat [arg [arg [arg]]] etc.

C:\Users\me\Desktop>arr 1 "2 3" 4
arr[] has a length of 3.
arr[0] = 1
arr[1] = 2 3
arr[2] = 4

C:\Users\me\Desktop>arr the quick brown fox jumps over the lazy dog, and so forth.
arr[] has a length of 12.
arr[0] = the
arr[1] = quick
arr[2] = brown
arr[3] = fox
arr[4] = jumps
arr[5] = over
arr[6] = the
arr[7] = lazy
arr[8] = dog,
arr[9] = and
arr[10] = so
arr[11] = forth.

这篇关于保存命令参数数组批的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆