cmd命令For分割字符串

<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

 

dos下面的批处理文件还是比较强大的,虽然刚开始觉得很不好用。遇到这么一个问题:用户输入一个新的版本号,解析其中的每个数字。例如一个版本号是"5.4.6",则要用"."分割开,然后提取其中的每个数字。处理命令为:

@REM 首先提示用户输入字符串,如5.4.6

@set /p inputVersion=version number:
FOR /F "tokens=1,2,3 delims=." %%a IN ("%inputVersion%") DO CALL SETVERSION %%a %%b %%c

 

setversion则又是另外一个bat文件,如下所示:

@SET major=
@SET minor=
@SET tiny=
@SET major=%1
@SET minor=%2
@SET tiny=%3

 

dos中的for语句的do后面只能接一个命令,如果用goto的话,不知道参数怎么传递,所以只好调用另外一个bat文件了。

对于上面的for语句要注意了。delims表示分隔符,tokens表示分割后的哪些字符需要传递到for循环中,也就是要进行do后面的命令行处理。如果输入5.4.6,那么1表示5,2表示4,3表示6,4就是空的了。如果tokens=1,则表示只把5传入do语句。如果tokens=1,2,3则表示4,5,6都要进行处理。奇怪的现象是,%%a代表第一个字符串,而2、3个字符串则是默认由%%a增加,即%%b, %%c表示。不知道如果变量不是%%a,后面的变量会是怎么表示。

 

你还可以参看下面的例子,该例子引用自:http://www.ss64.com/nt/for_f.html 这个例子比windows帮助上的说明要详细。

 

 

 

Extracting data from this text file:

January,Snowy,02
February,Rainy,15
March,Sunny,25

FOR /F "tokens=1,3 delims=," %%G IN (weather.txt) DO @echo %%G %%H

The tricky part is splitting up each the line into the right tokens, in this case I'm splitting on the comma character ',' this splits the line into 3 chunks of text and we pull out the first and third items with "tokens=1,3"

token1 , token2 , token3
%%G<ignored>%%H
January 02
February 15
March 25

%%G is declared in the FOR statement and %%H is implicitly declared via the tokens= option. You can specify up to 26 tokens via the tokens= line, provided this does not cause an attempt to declare a parameter higher than the letter 'Z'.

FOR parameter names are global, so in complex scripts which call one FOR statement from within another FOR statement you can refer to both sets of parameters. You cannot have more than 26 parameters active at any one time.

<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值