3

Below is my input 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" ]
}
---

#Hello

---
This is sample
---

```
var x=1;
entry.forEach(function(item){
    x=x++;
})
```

What I am expecting in output is, lines between first 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" ]
}

How can I achieve it? Using awk, I am able to achieve this only if i replace '---' with some string like 'start'/'end'.

awk '/start/{f=1;next} /end/{f=0;exit} f'  $FILE_PATH

2 Answers 2

5

Here's one solution:

awk '/^---/ {mark++; next} mark == 1 {print}' $FILE_PATH

Which produces:

{
  "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" ]
}

This increments a variable named mark every time it encounters the --- line. We only print lines when mark == 1. This is a nice solution because it will let you extract abitrary chunks of --- separated text. That is, if we wanted the second chunk of --- delimited text, we could run:

awk '/^---/ {mark++; next} mark == 2 {print}' $FILE_PATH

Which gives us:


#Hello

1

This is an option, giving your example:

sed -n '/^{$/,/^}$/p' file

Output:

{
  "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" ]
}
1
  • should probably be non-greedy.
    – user986805
    Nov 23, 2019 at 5:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .