0

Let's say i have a file that looks like this:

element1,element2  
element3,element4  
element5,element6

How can I read this file in bash and store it in an array as follows:

array={element1,element2,element3,element4,element5,element6}

Can someone help me with the code? Thanks!

Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45
Bai Radule
  • 61
  • 1
  • 6
  • The marked duplicate reads complete lines as array elements, here OP asks to read multiple elements per each line. – randomir Nov 20 '17 at 17:26

3 Answers3

2

You can ignore read altogether and simply use redirection after setting IFS, e.g.

$ IFS=$', \t\n'; a=($(<file)); declare -p a
declare -a a='([0]="element1" [1]="element2" [2]="element3" [3]="element4" \
[4]="element5" [5]="element6")'
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
1

Instead of reading line by line, then spliting by comma, you could do:

IFS=,$'\n' read -d '' -r -a array <file

This will:

  • use NUL character as line delimiter (-d ''), and this way (if your file does not contain null characters) read the complete file at once
  • split the "line" (i.e. the complete file) in fields using IFS, which is set to comma and newline, IFS=,$'\n'
  • store all words/elements in array.

Output:

$ printf "%s\n" "${arr[@]}"
element1
element2
element3
element4
element5
element6
randomir
  • 17,989
  • 1
  • 40
  • 55
0

You can use this bash code:

while IFS='' read -r line || [[ -n "$line" ]]; do
  array+=("$line")
done < "$1"

echo ${array[@]}

This read the content of the file that you specify by argument line and reads line by line while stores the values in a bash array.

Bye!

A.Villegas
  • 462
  • 7
  • 18