缩进并用字符串换行连续的匹配行

Indent and wrap consecutive matching lines with string

我想将包含代码片段的格式可预测的文件转换为 Markdown。该文件如下所示:

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

...

sedsort(小写 - 前面可能有空格)开头的行应该用```(Markdown开始/结束代码标记)包裹,缩进4空格,并且该节前后各有 1 个空行。带有 sedsort 的连续行应包含在同一编码部分内。最终的 Markdown 文件应如下所示:

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

我最感兴趣的是 awk/sed/bash 解决方案,但也欢迎提出其他建议。

可能是这样的:

awk '
     ~ /^(sed|sort)$/ {
        print "\n    ```"
        while ( ~ /^(sed|sort)$/) {
            sub(/^[ \t]*/, "    ")
            print
            if (!getline) {
                print "    ```\n"
                exit
            }
        }
        print "    ```\n"
    }
    1'

输出:

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

另一个 awk 变体:
(逻辑和另一个答案很相似)

awk '
    BEGIN{p=0}
    /^ *(sed|sort)/{
        if(!p)print "```";
        p=1;
        print "    " [=10=];
        next
        }
    p{
        print "```"
        p=0
     }
     1;
     END{
         if(p)print "```"
        }' my_commands.txt

输出:

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