2013-03-02 82 views
0

有人請告知什麼它在bash函數中讀取文件並從中創建一個數組?謝謝BASH - 尋求名稱功能,然後

+0

什麼是你想實現什麼? – 2013-03-02 00:22:38

+1

可能重複http://stackoverflow.com/questions/9736202/bash-read-file-line-into-array – jitendra 2013-03-02 00:24:52

+0

正在讀取文件並從文件數組創建...是一個直接函數,但我找不到它 – user2093552 2013-03-02 00:26:42

回答

1

我目前使用的窗口,以便沒有慶典在這裏,但你這是怎麼做到這一點:

value=0; 

while read line 
do 
value=`expr $value + 1`; 
arr[$value]=$line; 

done < "myfile" 
+1

是什麼讓你覺得在bash中存在一個函數呢? – 2013-03-02 00:28:35

+0

或者:'declare -a arr =($(cat myfile))' – Swiss 2013-03-02 00:31:43

+0

是的,100%;-)我用過它.. – user2093552 2013-03-02 00:35:22

1

我認爲你正在尋找內置mapfile

help mapfile

mapfile: mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] 
    Read lines from the standard input into an indexed array variable. 

    Read lines from the standard input into the indexed array variable ARRAY, or 
    from file descriptor FD if the -u option is supplied. The variable MAPFILE 
    is the default ARRAY. 

    Options: 
     -n count Copy at most COUNT lines. If COUNT is 0, all lines are copied. 
     -O origin Begin assigning to ARRAY at index ORIGIN. The default index is 0. 
     -s count Discard the first COUNT lines read. 
     -t    Remove a trailing newline from each line read. 
     -u fd    Read lines from file descriptor FD instead of the standard input. 
     -C callback  Evaluate CALLBACK each time QUANTUM lines are read. 
     -c quantum  Specify the number of lines read between each call to CALLBACK. 

    Arguments: 
     ARRAY    Array variable name to use for file data. 

    If -C is supplied without -c, the default quantum is 5000. When 
    CALLBACK is evaluated, it is supplied the index of the next array 
    element to be assigned and the line to be assigned to that element 
    as additional arguments. 

    If not supplied with an explicit origin, mapfile will clear ARRAY before 
    assigning to it. 

    Exit Status: 
    Returns success unless an invalid option is given or ARRAY is readonly or 
    not an indexed array.