我正在學習在 Bash 中撰寫腳本。我有一個 CSV 檔案,其中包含下一行:
numbers,one,two,three,four,five
colors,red,blue,green,yellow,white
custom-1,a,b,c,d,e
custom 2,t,y,w,x,z
需要從中創建陣列,其中第一個條目是陣列名稱,例如。
number=(one,two,three,four,five)
colors=(red,blue,green,yellow,white)
custom-1=(a,b,c,d,e)
custom 2=(t,y,w,x,z)
這是我的腳本:
IFS=","
while read NAME VALUES ; do
declare -a $NAME
arrays =($NAME)
IFS=',' read -r -a $NAME <<< "${VALUES[0]}"
done < file.csv
當我嘗試使用僅包含兩個第一個字串(數字和顏色)的 csv 檔案時,代碼運行良好。如果我嘗試使用數字、顏色、custom-1、custom-2,在讀取 csv 時會出現錯誤:
./script.sh: line 5: declare: `custom-1': not a valid identifier
./script.sh: line 7: read: `custom 2': not a valid identifier
因為據我所知,bash 不允許在變數名中使用特殊字符。有什么辦法可以避免這種情況嗎?
uj5u.com熱心網友回復:
由于您不能將 CSV 檔案的第一列用作 bash 陣列名稱,因此一個選項是使用計數器(例如arrayN)生成有效名稱。如果您想使用第一列的值訪問您的資料,您還需要將它們與相應的計數器值一起存盤在某處。關聯陣列 ( declare -A names=()) 將是完美的。最后但并非最不重要的一點是,namerefs(declare -n arr=...從 bash 4.3 開始可用)將便于存盤和訪問您的資料。例子:
declare -i cnt=1
declare -A names=()
while IFS=',' read -r -a line; do
names["${line[0]}"]="$cnt"
declare -n arr="array$cnt"
unset line[0]
declare -a arr=( "${line[@]}" )
((cnt ))
done < foo.csv
現在,要訪問對應于 entry 的值custom 2,首先獲取相應的計數器值,宣告一個指向相應陣列的 nameref 并瞧:
$ cnt="${names[custom 2]}"
$ declare -n arr="array$cnt"
$ echo "${arr[@]}"
t y w x z
讓我們宣告一個函式以便于訪問:
getdata () {
local -i cnt="${names[$1]}"
local -n arr="array$cnt"
[ -z "$2" ] && echo "${arr[@]}" || echo "${arr[$2]}"
}
進而:
$ getdata "custom 2"
t y w x z
$ getdata "colors"
red blue green yellow white
$ getdata "colors" 3
yellow
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/375460.html
