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!

1
  • The marked duplicate reads complete lines as array elements, here OP asks to read multiple elements per each line. Commented Nov 20, 2017 at 17:26

3 Answers 3

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")'
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.