I was trying to declare a variable in Bash with a list of arrays, the question is, is it possible to traverse individual array's value in combination one by one in Bash script. For e.g.
#!/bin/bash -x
declare -a r_Arr=("east" "west" "north")
declare -a u_Arr=(12 233 131)
declare -a v_Arr=(33 54 34)
items="${r_Arr[*]} ${u_Arr[*]} ${v_Arr[*]}"
Now how do I get values like {east,12,33} and {west,233,54} from items
CodePudding user response:
You can use a for loop :
#!/bin/bash -x
declare -a r_Arr=("east" "west" "north")
declare -a u_Arr=(12 233 131)
declare -a v_Arr=(33 54 34)
items="${r_Arr[*]} ${u_Arr[*]} ${v_Arr[*]}"
for ((i=0; i<${#r_Arr[@]}; i )); do
echo "${r_Arr[i]}" "${u_Arr[i]}" "${v_Arr[i]}"
done
CodePudding user response:
You could use a while loop as follows:
counter=0
while [ $counter -lt ${#r_Arr[@]} ]
do
echo {${r_Arr[$counter]}","${u_Arr[$counter]}","${v_Arr[$counter]}}
((counter ))
done
This would result in the following output:
{east,12,33}
{west,233,54}
{north,131,34}
CodePudding user response:
Store data in a space separated newline separated text file. Use a while loop to read it. Use grep
and standard unix tools awk
to process it. Linux is used to line-based values.
filecontent=\
'east 12 33
west 322 131
north 54 34'
while IFS=' ' read -r direction num1 num2; do
echo "$direction $num1 $num2"
done <<<"$filecontent"
Even, if starting from arrays, first paste them together anyway, and then use the while loop presented above:
paste -sd' ' <(
printf "%s\n" "${r_arr[@]}"
) <(
printf "%s\n" "${u_arr[@]}"
) <(
printf "%s\n" "${v_arr[@]}"
)