以下是我的输入文件:
---
{
"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++;
})
```
我期望的输出是第一的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" ]
}
我该如何实现它?使用awk,我只能通过替换'来实现这一点---' 包含一些字符串,例如 'start'/'end'。
awk '/start/{f=1;next} /end/{f=0;exit} f' $FILE_PATH
答案1
这是一个解决方案:
awk '/^---/ {mark++; next} mark == 1 {print}' $FILE_PATH
其结果为:
{
"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" ]
}
mark
每次遇到行时,都会增加名为的变量---
。我们只在 时打印行mark == 1
。这是一个很好的解决方案,因为它可以让你提取任意块---
。也就是说,如果我们想要第二一大块---
分隔的文本,我们可以运行:
awk '/^---/ {mark++; next} mark == 2 {print}' $FILE_PATH
这给了我们:
#Hello
答案2
这是一个选项,举个例子:
sed -n '/^{$/,/^}$/p' file
输出:
{
"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" ]
}