cmd - trick tp parse array and get symbols in order/turn/sequence

First of all, there is a very useful refrencial site that you can use to query some information about cmd syntax and some tips. the site is ss64.com;

 

There is a interesting discussion on how to use the cmd to parse text from a file into array and process the array one by one, also he wants to fetch each of the elements individually.

 

The discussion is in this page: .bat script for creating Array from txt file.

 

to parse a record (separated by ., and we want to retrieve the 1,2,3 elemetns), here is the code that you can write.

 

 

for /F "tokens=1,2,3* delims=." %%x in ('echo 2012.249.0.0') do echo %%x.%%y.%%z

 

the output would be 

 

2012.249.0

 

and if you want to enter an line of text into an array, by loop through the file,  you can do this:

 

 

setlocal EnableDelayedExpansion
set i=0
for /F "delims=. tokens=1,2,3*" %%a in ('echo 2012.249.0.0') do (
   set /A i+=1
   set array[!i!]=%%a.%%b.%%c
)
set n=%i%

 

Once you have the array, you can loop through the array with this methods.

 

 

for /l %%a in (1,1,%n%) do echo !array[%%a]!

 

 

to make an subroutine, you can do this:

 

:theSub arrayName arrayLen
for /L %%i in (1,1,%2) do echo !%1[%%i]!
exit /B


:next
call :theSub array %n%

 

 

the whole demo files is available hrere:  

 

REM http://stackoverflow.com/questions/9448651/bat-script-for-creating-array-from-txt-file
REM
REM array_fields.bat
REM this script demonstrate how to parse a text file line by line to an array and fetch the element each individually
REM


for /F "tokens=1,2,3* delims=." %%x in ('echo 2012.249.0.0') do echo %%x.%%y.%%z
REM output 2012.249.0


setlocal EnableDelayedExpansion
set i=0
for /F "delims=. tokens=1,2,3*" %%a in ('echo 2012.249.0.0') do (
   set /A i+=1
   set array[!i!]=%%a.%%b.%%c
)
set n=%i%

REM to prin the array elements
for /l %%a in (1,1,%n%) do echo !array[%%a]!

goto :next

:theSub arrayName arrayLen
for /L %%i in (1,1,%2) do echo !%1[%%i]!
exit /B


:next
call :theSub array %n%

endlocal

 

你可能感兴趣的:(cmd)