populate bash array with BLOCKS of lines

Viewed 84

I have either a file (or the output of a command) that has block of lines separated by the empty line - like below:

1
2
3

4
5
6

cannot figure out how to populate bash (4.4.12) array with "block" of lines for each array cell, e.g.

arr[0]='
1
2
3'

array[1]='
4
5
6'

Looked around for similar threads with readarray, mapfile, played with IFS/read and other alternatives, but cannot figure out how to do the "blocks" of lines, not simply one-line-at-the time. What's the magic combo?

2 Answers

With bash:

declare -i c=0                      # set integer attribute

while IFS= read -r line; do
  [[ -z $line ]] && c+=1
  arr[$c]+="$line"$'\n'
done < file

declare -p arr                      # output array

Output:

declare -a arr=([0]=$'1\n2\n3\n' [1]=$'\n4\n5\n6\n')

Here's another approach on a similar SO thread:

while IFS= read -r -d '' rec
do
  arr2+=("${rec}")
done < <(awk '1' RS= ORS='\x0' file)

declare -p arr2
Related