I want to transpose a file using a bash script, but I'm having issues with echoing multidimensional arrays.
file.txt
has the following content:
name age
alice 21
ryan 30
Output the following:
name alice ryan
age 21 30
code
file_content=$(cat file.txt)
parent_array=()
while IFS= read -r line; do
IFS=' ' read -r -a split_array <<< "$line"
elements_len=${#split_array[@]}
for ((i=0; i<$elements_len; i++)); do
parent_array[$i]+="${split_array[$i]} "
done
done <<< "$file_content"
# Iterate over the multi-dimensional array
for ((i=0; i<${#parent_array[@]}; i++)); do
for ((j=0; j<${#parent_array[$i]}; j++)); do
echo "${parent_array[$i][$j]}"
done
done
error
$ bash transpose.sh
transpose.sh: line 13: ${parent_array[$i][$j]}: bad substitution
I tried to transpose the file 'file.txt' using a Bash script. I stored the content of 'file.txt' in a multidimensional array, but I am facing issues when trying to echo the elements. I would like to know how to iterate through this type of array in a Bash script.
Also, how can I remove the trailing space only for the last echo statement? I have attempted the following code, which prints all elements, but I am unable to skip the trailing space for the last echo at each index level:
for element in "${parent_array[@]}"; do
echo "$element"
done
This loop works for multidimensional arrays, but when echoing, it outputs the name 'name alice ryan ' instead of the desired 'name alice ryan'. How can I remove the trailing space only for the last echo statement? I posted this question on Stack Overflow. Please correct any grammatical mistakes and provide suggestions for improvement.