首页 > 解决方案 > 根据条件打印字符串之间的行

问题描述

我有一个(n R Markdown)脚本,其中包含纯文本以及分隔的 bash 代码块。我想将所有 bash 代码块提取到一个单独的文档中,并将标题作为代码上方的块作为注释。但是,如果未找到选项include,我只想打印代码块。示例脚本:echo

Here's some writing. Next code chunk should be included. 

```{bash, chunk-1, option=TRUE}
foo="bar"
```

Now one not to be included because it contains `include`.

```{bash, chunk-2, option=TRUE, include=FALSE}
foo2="bar2"
```

Another code chunk not to be included because it contains `echo`. 

```{bash, chunk-3, option=FALSE, echo=FALSE}
foo3="bar3"
```

Finally one that should be included because `include` and `echo` are not found.

```{bash, chunk-4, option=FALSE, another_option=TRUE}
foo4="bar4"
```

所需的输出将是

# chunk-1 
foo="bar"

# chunk-4
foo4="bar4"

块标题将始终位于前两个逗号之间,后面的其他选项以逗号分隔。

我一直在与awk. 以下获取评论 write,但不搜索includeor echo

awk '$0 ~ /^```$/ {p=0} 
     $1 ~ /^```{bash/ {p=1; print "\n# " substr($2, 1, length($2)-1); next}
     p'

标签: regexawksedr-markdown

解决方案


你可以使用这个awk

awk -F ', *' '/^```$/{p = 0} p;
/```{bash/ && !/ (include|echo)=/{print "#", $2; p=1}' file
# title-of-chunk
# here's some bash code
blah_blah="blah"

推荐阅读