使用字符串缩进和换行连续匹配行
问题描述:
我想将包含代码片段的可预测格式的文件转换为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
...
线开始sed
或sort
(小写 - 可具有在前面的空格)应与```
包裹(降价起始/结束码的标记)中,用4个空格缩进和具有1该部分之前和之后的空行。连续行sed
或sort
应包装在相同的编码部分。最终的降价文件应该是这样的:
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
```
答
另一个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
```
辉煌,谢谢!学到新东西('getline') – henfiber