How do I split a text file into an array by blank lines?

眉间皱痕 提交于 2021-02-16 14:19:28

问题


I have a bash command that outputs text in the following format:


Header 1
- Point 1
- Point 2

Header 2
- Point 1
- Point 2

Header 3
-Point 1
- Point 2

...

I want to parse this text into an array, separating on the empty line so that array[0] for example contains:

Header 1
- Point 1
- Point 2

And then I want to edit some of the data in the array if it satisfies certain conditions.

I was looking at something like this Separate by blank lines in bash but I'm completely new to bash so I don't understand how to save the output from awk RS=null to an array instead of printing it out. Could someone please point me in the right direction?


回答1:


You can use readarray command to populate a bash array after reading your file with gnu awk command with empty RS that lets awk split records on empty lines and using ORS as \0 (NUL) byte:

IFS= readarray -d '' arr < <(awk -v RS= -v ORS='\0' '1' file)

Check output:

echo "${arr[0]}"
Header 1
- Point 1
- Point 2

echo "${arr[1]}"
Header 2
- Point 1
- Point 2

echo "${arr[2]}"
Header 3
-Point 1
- Point 2

Online Demo



来源:https://stackoverflow.com/questions/57673497/how-do-i-split-a-text-file-into-an-array-by-blank-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!