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
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

2

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" ]
}
  • should probably be non-greedy. – bac0n Nov 23 '19 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.