读取 2 个数组,将第一个数组视为名称并从第二个数组开始填充

Read 2 arrays, treat first array as the name and fill it from second

我使用 curl 得到了 2 个数组 我用户 readarray <<<$(curl http://etc)

所以例如我得到了第一个数组的第一行 “最好的朋友”和第二个数组第一行“John Jim Piter”

如何将第一个数组的每一行视为 new_array_name 并使用 bash 从第二个数组填充它? 第一个数组的每一行必须被视为单独的数组名称并从第二个数组的每一行填充。

每个数组中有多行

更新。正如@choroba 提到的,我还需要替换变量名中的空格

我有 2 个数组: declare -a my_array=([0]=$'BEST FRIENDS' [1]=$'Second line')

和第二个数组 = declare -a my_array2=([0]=$'JOHN Jim Piter' [1]=$'This is the test') 我需要将第一个数组中的每一行视为变量名,将第二个数组中的每一行视为值。 像这样 - BEST FRIENDS=JOHN Jim Piter

这结合了几种技术,每一种技术都是我们知识库中已有内容的复制。

  • how to trim whitespace from a bash variable
  • indirect variable assignment in bash
#!/usr/bin/env bash
array1=( "Best Friends" "Worst Enemies" )
array2=( "Jim John Pieter" "Alfred Joe" )

for idx in "${!array1[@]}"; do
  varname=${array1[$idx]//" "/}              # remove spaces from target name
  read -r -a "$varname" <<<"${array2[$idx]}" # read into target
  declare -p "$varname" >&2     # show what we did
done

这将创建两个数组,如下所示:

declare -a BestFriends=([0]="Jim" [1]="John" [2]="Pieter")
declare -a WorstEnemies=([0]="Alfred" [1]="Joe")

...作为数组,可以用作:

for friend in "${BestFriends[@]}"; do
  echo "I sure do enjoy hanging with $friend!"
done