Regex 根据条件打印字符串之间的行

Regex 根据条件打印字符串之间的行,regex,awk,sed,r-markdown,Regex,Awk,Sed,R Markdown,我有一个(nRmarkdown)脚本,它包含纯文本和分隔的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 i

我有一个(nRmarkdown)脚本,它包含纯文本和分隔的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
。下面获取注释写入,但不搜索
include
echo

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

您可以使用此
awk

awk -F ', *' '/^```$/{p = 0} p;
/```{bash/ && !/ (include|echo)=/{print "#", $2; p=1}' file

除了文本文件中的关键字
bash
,这个问题与bash标记无关。请发布更多输入和预期输出的清晰示例。您获取示例输出的逻辑不清楚,请编辑它并告知我们。请仅提供一个示例输入文件,其中包含您要匹配的块和您不想匹配的块,然后提供给定该输入的预期输出文件。如果没有这一点,就很难测试一个潜在的解决方案,看看它是否真的有效。
# title-of-chunk
# here's some bash code
blah_blah="blah"