获取特殊字符模式之间的行

PKV*_*PKV 3 command-line awk text-processing

下面是我的输入文件:

---
{
  "date":"2015-09-24",
  "title":"Getting Started with Git",
  "template":"post",
  "thumbnail":"content/thumbnails/test.jpeg",
  "slug":"getting-started-with-git",
  "categories":[ "cat1", "Focus", "Mustang" ],
  "tags":[ "Fiesta", "Focus", "Mustang" ]
}
---

#Hello

---
This is sample
---

```
var x=1;
entry.forEach(function(item){
    x=x++;
})
```
Run Code Online (Sandbox Code Playgroud)

我在输出中期望的是,2行之间的' --- '

{
  "date":"2015-09-24",
  "title":"Getting Started with Git",
  "template":"post",
  "thumbnail":"content/thumbnails/test.jpeg",
  "slug":"getting-started-with-git",
  "categories":[ "cat1", "Focus", "Mustang" ],
  "tags":[ "Fiesta", "Focus", "Mustang" ]
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现它?使用awk,只有当我将 ' --- '替换为诸如 'start'/'end' 之类的字符串时,我才能实现这一点。

awk '/start/{f=1;next} /end/{f=0;exit} f'  $FILE_PATH
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 5

这是一种解决方案:

awk '/^---/ {mark++; next} mark == 1 {print}' $FILE_PATH
Run Code Online (Sandbox Code Playgroud)

其中产生:

{
  "date":"2015-09-24",
  "title":"Getting Started with Git",
  "template":"post",
  "thumbnail":"content/thumbnails/test.jpeg",
  "slug":"getting-started-with-git",
  "categories":[ "cat1", "Focus", "Mustang" ],
  "tags":[ "Fiesta", "Focus", "Mustang" ]
}
Run Code Online (Sandbox Code Playgroud)

mark每次遇到该---行时,都会增加一个命名的变量。我们只在mark == 1. 这是一个很好的解决方案,因为它可以让您提取任意的---分隔文本块。也就是说,如果我们想要第二---分隔文本,我们可以运行:

awk '/^---/ {mark++; next} mark == 2 {print}' $FILE_PATH
Run Code Online (Sandbox Code Playgroud)

这给了我们:


#Hello

Run Code Online (Sandbox Code Playgroud)