LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   bash split array and assign a variable to an element (http://www.linuxquestions.org/questions/programming-9/bash-split-array-and-assign-a-variable-to-an-element-4175452399/)

eamesj 03-02-2013 11:28 AM

bash split array and assign a variable to an element
 
Hi,

wonder if you can help. I have a bash script which is generating an array...

Quote:

echo "Enter the list, type 'quit' to exit"
while read -r input ; do
[[ $input == quit ]] && break
array+=( $input )
done
echo ${array[@]}
which when the input is
1 a z
2 b y
3 c x
quit

gives the array three elements. Is there a way i can split these elements based on column and assign them to a variable?

so if
column1=$number (1, 2 and 3)
column2=$letter (a, b and c)
column3=$anotherletter (z, y and x)

i can perform an action on each e.g.

Quote:

for index in ${!array[*]} ; do
echo "$array[1] has value ${number}, letter ${letter}"
done
Thanks,

David the H. 03-02-2013 12:41 PM

Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.

Your best bet is simply to use another read command, either with separate variables or another array.

Code:

for i in "${!array[@]}"; do
    read -r number letter anotherletter <<<"${array[i]}"
    echo "$array[i] has value ${number}, letter ${letter}, and letter $anotherletter"
done


string manipulations in bash

eamesj 03-02-2013 12:56 PM

awesome david, works well. thanks

David the H. 03-02-2013 01:19 PM

Great. Please mark the thread as solved.

Oh, and I almost forgot, be sure to always quote your variable expansions, otherwise shell word-splitting will take place (with a few minor exceptions, such as inside [[..]]).
Code:

while read -r input ; do
    [[ $input == quit ]] && break
    array+=( "$input" )
done
echo "${array[@]}"

Without the quotes, the initial $input value will be split into multiple array elements, and the final echo command will have all entries printed with only single spaces between them, regardless of their original formatting.

It's vital in scripting to understand how the shell handles arguments and whitespace. Learn how to do it right!
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes


All times are GMT -5. The time now is 10:52 PM.