如何用空行将文本文件拆分为数组?
我有一个bash命令,它以以下格式输出文本:
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
...
我想将此文本解析为一个数组,在空行上分开,以便array [0]例如包含:
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.
我正在查看类似这样的内容以bash中的空白行分隔但是我对bash完全陌生,所以我不了解如何将awk RS = null的输出保存到数组而不是将其打印出来.有人可以指出正确的方向吗?
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?
使用gnu awk
命令读取文件后,可以使用 readarray
命令填充bash数组空的 RS
,它允许 awk
在空行上分割记录,并使用 ORS
作为 \ 0
(NUL)字节:
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)
检查输出:
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