Indent and wrap consecutive matching lines with string

I would like to convert a predictably-formatted file containing code snippets into Markdown. The file looks like this:

MY CODE SNIPPETS          2015-05-01

This file contains useful code snippets for every day usage
in the Linux command line.

SED
  sed 's/(.*)1//g'                  # Modify anystring1 to anystring2
  sed '/^ *#/d; /^ *$/d'                 # Remove comments and blank lines

SORT
  sort -t. -k1,1n -k2,2n -k3,3n -k4,4n   # Sort IPV4 ip addresses

...

Lines starting with sed or sort (lowercase – may have whitespace in front) should be wrapped with ``` (Markdown starting / ending code markers), be indented with 4 spaces and have 1 blank line before and after the section. Consecutive lines with sed or sort should be wrapped inside the same coding section. The final Markdown file should look like this:

MY CODE SNIPPETS          2015-05-01

This file contains useful code snippets for every day usage
in the Linux command line.

SED

    ```
    sed 's/(.*)1//g'                  # Modify anystring1 to anystring2
    sed '/^ *#/d; /^ *$/d'                 # Remove comments and blank lines
    ```

SORT

    ```
    sort -t. -k1,1n -k2,2n -k3,3n -k4,4n   # Sort IPV4 ip addresses
    ```

I would be mostly interested in an awk/sed/bash solution, but other suggestions would be welcome.


Source: bash

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.