如何使用 AWK 提取 YAML 块

How can I extract a YAML block using AWK

我想使用 AWK 从文件中提取以“---”分隔的 YAML 块,如下所示:

---
title: "This is a title"
sourceEditionDate: 1927-01-01
languages:
  - "latin"
tags:
  - poetry
---

Some other text I do not want to extract

结果如下:

title: "This is a title"
sourceEditionDate: 1927-01-01
languages:
  - "latin"
tags:
  - poetry

到目前为止我已经尝试过这种方法

awk '/---/{p=0};p;/---/{p=1}' file

但我仍然得到整个文件,包括不需要的最后一行。

$ awk '/---/{f=!f; next} f' file
title: "This is a title"
sourceEditionDate: 1927-01-01
languages:
  - "latin"
tags:
  - poetry

还有 awk 你可以得到相同的结果:

awk '!/---/' file
title: "This is a title"
sourceEditionDate: 1927-01-01
languages:
  - "latin"
tags:
  - poetry