1

I have a file with the following content:

list:

blue,none
red,none
orange,plot
   baseball   ,     none
university,none
school,none
desk,plot
monitor,none
earphone,none

I need to read this file, remove spaces and store each column in a different array.

script:

output_names=()
output_plots=()

while read line           
do
    item=$(echo -e "${line}" | tr -d '[[:space:]]')
    item=$(echo $item | tr "," "\n")
    output_names+=(${item[0]});
    output_plots+=(${item[1]});
done <list

echo "** output_names:";
for item in ${output_names[*]}
do
    echo $item
done

echo "** output_plots:";
for item in ${output_plots[*]}
do
    echo $item
done

However it does not work as I expect. What is wrong? and how to fix this code?

Note

If somebody has a solution to store the data in a single array with different keys output['names'][*] and output['plots'][*], that would be highly appreciated as I do not know how to do it.

Outputs:

** output_names:
blue
none
red
none
orange
plot
baseball
none
university
none
school
none
desk
plot
monitor
none
earphone
none
** output_plots:
2
  • output_names=( $(cut -d',' -f1 infile) ); output_plots=( $(cut -d',' -f2 infile) ); for item in ... do... Commented Mar 25, 2015 at 0:42
  • @ar2015; note that the (expensive) tr commands can be avoided since the shell is capable of doing deletions ${var//pattern} and substitutions ${var//pattern/repl}. Commented Mar 25, 2015 at 1:02

2 Answers 2

2

The problem with your code is the tr command and your (wrong) assumptions about item[0] and item[1].

There are of course various ways to handle that; here is one way (staying close to your approach):

while IFS=, read left right
do
    output_names+=( "${left// }" )
    output_plots+=( "${right// }" )
done <list

(I've only depicted the loop changes, the rest of your code can stay as is.)

0

This returns a string with spaces:

item=$(echo $item | tr "," "\n")

change it like this to have an array:

item=($(echo $item | tr "," "\n"))

output:

** output_names:
blue
red
orange
baseball
university
school
desk
monitor
earphone
** output_plots:
none
none
plot
none
none
none
plot
none
none

There may be better ways to achieve your task tough

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.