How to create an array from txt file within a batch file?

后端 未结 3 529
刺人心
刺人心 2021-01-14 05:40

I have a txt file with below data

aaaa 1000 2000
bbb  3000 4000
cccc 5000 
ffffd  6000 7000 8000 

The numbers of rows in this file are not fi

相关标签:
3条回答
  • 2021-01-14 05:54

    try this:

    @echo off
    for /F "tokens=1,2*" %%x in  (myFile.txt) do echo %%x
    

    the double % is required for use in a batch file, but you can test it on the cmd line with single %s.

    in a nutshell, the for will iterate over myFile.txt break each line into two tokens using the default delimiter (space).

    0 讨论(0)
  • 2021-01-14 06:00

    To create the array:

    setlocal EnableDelayedExpansion
    
    set i=0
    for /F %%a in (theFile.txt) do (
       set /A i+=1
       set array[!i!]=%%a
    )
    set n=%i%
    

    To print array elements:

    for /L %%i in (1,1,%n%) do echo !array[%%i]!
    

    If you want to pass the array name and lenght as subroutine parameters, then use this way:

    call theSub array %n%
    
    :theSub arrayName arrayLen
    for /L %%i in (1,1,%2) do echo !%1[%%i]!
    exit /B
    
    0 讨论(0)
  • 2021-01-14 06:07

    try this and call it from anywhere

    @echo off
    
    for /f "usebackq" %%a in ('%2') do set d=%%~a
    for /f "usebackq tokens=* delims=%d%" %%G in ('%3')  do set %1=%%~G
    
    set /a i=-1
    
    
    for %%h in (!%1!) do (
    set /a i+=1
    set %1[!i!]=%%h
    )
    
    0 讨论(0)
提交回复
热议问题