標籤:bat 分割字串 split
最近有有個小需求需要將shell 指令碼的功能挪到windows中,但發現shell中有數組概念,但windows中卻沒有,同時shell中有很多方式處理字串分割,但bat中就顯得比較雞肋,經過一番尋找,終於有了方案(Stack Overflow:http://stackoverflow.com/questions/1707058/how-to-split-a-string-in-a-windows-batch-file):
方案: 通過for迴圈處理,而處理的方式又可以分兩種,一種是普通for,一種是for的檔案處理方式:
方案一:
@echo off & setlocalrem 注意這裡的s定義,其值不是使用雙引號引起來的rem also works for comma-separated lists, e.g. ABC,DEF,GHI,JKLset s=AAA BBB CCC DDD EEE FFFfor %%a in (%s%) do echo %%a
方案二:is the best for (most) arbitrary delimiter characters.
@echo off & setlocalset s=AAA BBB CCC DDD EEE FFFset t=%s%:loopfor /f "tokens=1*" %%a in ("%t%") do ( echo %%a rem 將截取剩下的部分賦給t,其實這裡可以使用延遲變數開關 set t=%%b )if defined t goto :loop
有個老兄給了個更完整的(用到了延遲變數):
@echo offsetlocal ENABLEDELAYEDEXPANSIONREM Set a string with an arbitrary number of substrings separated by semi colonsset teststring=The;rain;in;spainREM Do something with each substring:stringLOOP REM Stop when the string is empty if "!teststring!" EQU "" goto END for /f "delims=;" %%a in ("!teststring!") do set substring=%%a REM Do something with the substring - REM we just echo it for the purposes of demo echo !substring!REM Now strip off the leading substring:striploop set stripchar=!teststring:~0,1! set teststring=!teststring:~1! if "!teststring!" EQU "" goto stringloop if "!stripchar!" NEQ ";" goto striploop goto stringloop):ENDendlocal
還有這樣的:
set input=AAA BBB CCC DDD EEE FFFset nth=4for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%aecho %nthstring%
其實Powershell裡可能有更多的內建函數可以使用:
PS C:\> "AAA BBB CCC DDD EEE FFF".Split()
還有人提出用vbscrip代替bat:
Set objFS = CreateObject("Scripting.FileSystemObject")Set objArgs = WScript.Argumentsstr1 = objArgs(0)s=Split(str1," ")For i=LBound(s) To UBound(s) WScript.Echo s(i) WScript.Echo s(9) ‘ get the 10th elementNextusage:c:\test> cscript /nologo test.vbs "AAA BBB CCC"
Bat 處理字串分割 (split功能)