使用字符串缩进和换行连续匹配行

问题描述:

我想将包含代码片段的可预测格式的文件转换为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/\12/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(小写 - 可具有在前面的空格)应与```包裹(降价起始/结束码的标记)中,用4个空格缩进和具有1该部分之前和之后的空行。连续行sedsort应包装在相同的编码部分。最终的降价文件应该是这样的:

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/\12/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 ' 
    $1 ~ /^(sed|sort)$/ { 
     print "\n ```" 
     while ($1 ~ /^(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/\12/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 
    ``` 
+0

辉煌,谢谢!学到新东西('getline') – henfiber

另一个awk变体:
(逻辑非常类似于其他回答)

awk ' 
    BEGIN{p=0} 
    /^ *(sed|sort)/{ 
     if(!p)print "```"; 
     p=1; 
     print " " $0; 
     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/\12/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 
``` 
+0

感谢您的替代解决方案。我已经接受了另一个答案,但你的工作也很棒(使用'p'标志有一个很好的替代方法,两个小的注释:1.'''''应该缩进以及4个空格(只要改成'print “'''''''2.其他答案('$ 1〜/ ^(sed | sort)$ /')的正则表达式似乎更好一些,因为它考虑了'sed/sort'命令(使用'$ 1')和美元'''在最后确保我们不会匹配以'sed/sort'开头的其他单词 – henfiber

+0

当然......正如我已经说过的,逻辑非常多类似于其他答案... – anishsane