簡體   English   中英

從文件填充數組

[英]Populating array from file

我已經搜索過谷歌,卻找不到答案。 我正在從文件填充數組的功能:

#!/bin/bash

PusherListV2=()
PusherListV3=()

getArray () {
        if ! [ -f $2 ]; then return 2
        fi
        i=0
        while read p; do
                PusherList$1[$i]="$p"
                ((i++))
        done <$2
}

getArray V2 /tmp/test.txt

echo ${PusherListV2[@]}

我遇到這種錯誤:

./test.sh: line 11: PusherListV2[0]=p01: command not found
./test.sh: line 11: PusherListV2[1]=p02: command not found
./test.sh: line 11: PusherListV2[2]=p03: command not found
./test.sh: line 11: PusherListV2[3]=p04: command not found
./test.sh: line 11: PusherListV2[4]=p05: command not found

有人可以幫我嗎?

您不能在分配中使用變量替換來構造變量名稱。 這不起作用:

PusherList$1[$i]="$p"

用。。。來代替:

eval PusherList$1[$i]=\"\$p\"

甚至僅僅是這個(如shekhar suman所說,引號在這里並不是特別有用):

eval PusherList$1[$i]=\$p

只要您控制$1$i ,就應該安全地使用eval

使用readarray有一個非常簡單的解決方案。 這是測試文件:

$ cat file.tmp
first line
second line
third line

現在,我讀取文件並將行存儲在數組中:

$ readarray mytab < file.tmp

最后,我檢查數組:

$ declare -p mytab
declare -a mytab='([0]="first line
" [1]="second line
" [2]="third line
")'

如您所見,這些行與\\n存儲在一起。 -t除去它們。

現在要解決您的問題,您可以使用新的nameref屬性(bash 4.3+)在函數中通過引用傳遞數組,無需使用eval

PusherListV2=()
PusherListV3=()

getArray () array file
{
    local -n array="$1"    # nameref attribute
    local file="$2"

    test -f "$file" || return 2

    readarray -t array < "$file"
}

getArray PusherListV2 /tmp/test.txt

echo "${PusherListV2[@]}"    # always "" arround when using @

如果您仍然想通過V2而不是PusherListV2 ,則只需編寫

    local -n array="PusherList$1"    # nameref attribute

在功能上。

如果我理解正確,則需要一個帶有兩個參數的函數:

  • 第一個參數是將附加到PusherList以獲得字符串名稱的字符串
  • 第二個參數是文件名

該函數應將文件的每一行放入數組中。

簡單,在Bash中≥4:

getArray() {
    [[ -f $2 ]] || return 2
    # TODO: should also check file is readable
    mapfile -t "PusherList$1" < "$2"
    # TODO: check that mapfile succeeded
    # (it may fail if e.g., PusherList$1 is not a valid variable name)
}

mapfile-t選項,以便修剪尾隨的換行符。

注意。 這很可能是最有效的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM