首页 > 解决方案 > How to split a variable with text content on an empty line

问题描述

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!

标签: linuxbashubuntufile-io

解决方案


替换\n\n为数据中未包含的内容,将 IFS 设置为它,填充数组。

#! /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//$'\n\n'/$separator})

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

printf '<%s>\n' "${arr[@]}"

推荐阅读