2

I have the following code: Text read from file: "E" "01" "Adv - Initial" "07/11/2017"

And I would like it be stored in an array like below: array[0] = "E" array[1] = "01" array[2] = "Adv - Initial" array[3] = "07/11/2017"

I have tried: itemData=( "$line" ) in a while loop. But I don't get the results I want.

  • 3
    Is Text read from file: part of the file, or part of the instructions? Are there multiple lines to loop over (why else were you looping?). – Jeff Schaller Jul 10 '17 at 16:59
  • You might want to investigate the bash mapfile command – glenn jackman Jul 10 '17 at 20:10
1

One of the problems is "Adv - Initial" will be broken in Adv, -, and Initial. Need to play with changing IFS.

#/bin/bash

savIFS=$IFS
IFS=\"
array=($line)
IFS=$savIFS

echo "${array[1]}"
echo "${array[3]}"
echo "${array[5]}"
echo "${array[7]}"
0

You want to append your current array. To achieve this do

declare -a array

to declare your array and

array+=("$line")

to append an element to your array.

Bash Reference Manual:

In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.

Not the answer you're looking for? Browse other questions tagged or ask your own question.