I get 2 arrays using curl
I user readarray <<<$(curl http://etc)
So for example I got first array first line "Best friends" and second array first line "John Jim Piter"
How I can treat each line of the first array as new_array_name and fill it from the second array using bash? Each line of first array must be treat as separated array name and fill from each line of the second array.
Where are multiple line in each array
UPD. As @choroba mention also I need replace whitespace in variable name
I have 2 arrays:
declare -a my_array=([0]=$'BEST FRIENDS' [1]=$'Second line')
and 2nd array = declare -a my_array2=([0]=$'JOHN Jim Piter' [1]=$'This is the test')
I need treat each line from first array as variable name and each line from second array as value.
Like this - BEST FRIENDS=JOHN Jim Piter
CodePudding user response:
This combines several of techniques, each of which is already a duplicate of something already in our knowledge base.
- bash script iterate through two variables in lock step
- 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
This creates two arrays, as follows:
declare -a BestFriends=([0]="Jim" [1]="John" [2]="Pieter")
declare -a WorstEnemies=([0]="Alfred" [1]="Joe")
...which, being arrays, can be used as:
for friend in "${BestFriends[@]}"; do
echo "I sure do enjoy hanging with $friend!"
done