简体   繁体   English

如何用空行将文本文件拆分为数组?

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

I have a bash command that outputs text in the following format: 我有一个bash命令,它以以下格式输出文本:


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: 我想将此文本解析为一个数组,在空行上进行分隔,以使array [0]例如包含:

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. 我当时在看bash中用空白行分隔的内容,但是我对bash还是陌生的,所以我不知道如何将awk RS = null的输出保存到数组中,而不是将其打印出来。 Could someone please point me in the right direction? 有人能指出我正确的方向吗?

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: 您可以使用带有空RS gnu awk命令读取文件后,使用readarray命令填充bash数组,该命令使awk在空行上拆分记录,并使用ORS作为\\0 (NUL)字节:

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 在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM