2

So I have many Jekyll posts in _posts with metadata YAML in the header, including categories, like this:

---
excerpt: "I am an excerpt"
categories:
- tips
- programming
- howto
- another-tag
layout: blog
title: I am a Page Title
created: 1267026549
permalink: blog/27-05-2017/clean-url-goes-here
---

So I know how to grep for the categories line and show n lines after (-An)... but is there a way to make it show all the following lines that begin with - as, obviously, each post has a different number. Maybe all lines until layout?

  • will layout always be a stop point for all matched lines? – RomanPerekhrest May 27 '17 at 12:08
2

The recommended tool for text processing is awk.

Try this:

awk '/categories/,/layout/ { if (!/layout/) print }' your_file

This command prints everything starting from categories until layout without this line itself.

Output:

categories:
- tips
- programming
- howto
- another-tag

If you only want to have the items between categories and layout you could simply add a second pattern to the if condition like this:

awk '/categories/,/layout/ { if (!/layout/ && !/categories/) print }' your_file

Then your output will look like this:

- tips
- programming
- howto
- another-tag
  • Brilliant, Thanks, @john-goofy - perfect. – Nick May 27 '17 at 20:14
1

If you can use pcregrep (Perl-compatible regular expressions):

pcregrep -M 'categories.*(\n-.*)*' file

or using lookahead assertion:

pcregrep -M 'categories(.|\n)*(?=layout)' file
1
sed -e '/^categories:/,/^[^-]/!d;//d' yourfile
0

Here's a way to do it with awk. When you find the header line, print it, and keep getting the next line and printing it, as long as the next line starts with a -.

awk '$0=="categories:" { do { print; getline } while (/^-/) }'

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.