Extract section of file to a variable, from within a shell script

Viewed 944

I'm writing a script intended to run under bash in OS X. I have Markdown files that look like this:

# File name

## Heading 1

Some text


## Heading 2

* List item 1
* List item 2


## Some other section
...

I'm trying to read everything inside Heading 2 into a variable, and I've tried using sed, grep, and perl, but can't get a working solution. Of those tools, it looked to (in theory) be possible and easiest with Perl, especially given that I need multiple lines. It looks like this regex works (at least with javascript syntax):

## Heading 2\s+(.+)\s+

I'd like to keep it a one-liner, and stick to only tools available on stock OS X (El Capitan, 10.11). Assume I only know "Heading 2" up front, not the following header caption.

3 Answers
Related