Bash从文件读取到关联数组

时间:2021-08-26 06:09:11

I'm trying to write a script in bash using an associative array. I have a file called data:

我正在尝试使用关联数组在bash中编写脚本。我有一个名为data的文件:

a,b,c,d,e,f
g,h,i,j,k,l

The following script:

以下脚本:

oldIFS=${IFS}
IFS=","

declare -A assoc
while read -a array
do 
  assoc["${array[0]}"]="${array[@]"
done

for key in ${!assoc[@]}
do
  echo "${key} ---> ${assoc[${key}]}"
done 

IFS=${oldIFS}

gives me

给我

a ---> a b c d e f

g ---> g h i j k l

I need my output to be:

我需要输出:

a b ---> c d e f

g h ---> i j k l

1 个解决方案

#1


15  

oldIFS=${IFS}
IFS=","

declare -A assoc
while read -r -a array
do 
  assoc["${array[0]} ${array[1]}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
  echo "${key} ---> ${assoc[${key}]}"
done

IFS=${oldIFS}

data:

数据:

a,b,c,d,e,f
g,h,i,j,k,l

Output:

输出:

a b ---> c d e f
g h ---> i j k l

Uses Substring Expansion here ${array[@]:2} to get substring needed as the value of the assoc array. Also added -r to read to prevent backslash to act as an escape character.

在这里使用子串扩展$ {array [@]:2}来获取需要的子串作为assoc数组的值。还添加-r以读取以防止反斜杠充当转义字符。

Improved based on @gniourf_gniourf's suggestions:

根据@ gniourf_gniourf的建议改进:

declare -A assoc
while IFS=, read -r -a array
do 
    ((${#array[@]} >= 2)) || continue
    assoc["${array[@]:0:2}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
    echo "${key} ---> ${assoc[${key}]}"
done

#1


15  

oldIFS=${IFS}
IFS=","

declare -A assoc
while read -r -a array
do 
  assoc["${array[0]} ${array[1]}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
  echo "${key} ---> ${assoc[${key}]}"
done

IFS=${oldIFS}

data:

数据:

a,b,c,d,e,f
g,h,i,j,k,l

Output:

输出:

a b ---> c d e f
g h ---> i j k l

Uses Substring Expansion here ${array[@]:2} to get substring needed as the value of the assoc array. Also added -r to read to prevent backslash to act as an escape character.

在这里使用子串扩展$ {array [@]:2}来获取需要的子串作为assoc数组的值。还添加-r以读取以防止反斜杠充当转义字符。

Improved based on @gniourf_gniourf's suggestions:

根据@ gniourf_gniourf的建议改进:

declare -A assoc
while IFS=, read -r -a array
do 
    ((${#array[@]} >= 2)) || continue
    assoc["${array[@]:0:2}"]="${array[@]:2}"
done < data

for key in "${!assoc[@]}"
do
    echo "${key} ---> ${assoc[${key}]}"
done