Skip to content
Advertisement

How to split a variable with text content on an empty line [closed]

how can i split a variable with text content by every empty line? Maybe into an array or something like this …

Example:

line1
line2
line3

line4
line5

line6
line7
line8
line9

maybe into:

array[0]: line1
          line2
          line3 

array[1]: line4
          line5

...

Thanks!

Advertisement

Answer

Replace nn with something not contained in the data, set IFS to it, populate the array.

#! /bin/bash
in='line1
line2
line3

line4
line5

line6
line7
line8
line9'

separator=$'xff' # or whatever char not appearing in the data

${IFS+"false"} && unset oldifs || oldifs="$IFS"
IFS=$separator
arr=(${in//$'nn'/$separator})

${oldifs+"false"} && unset IFS || IFS="$oldifs"

printf '<%s>n' "${arr[@]}"
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement