regex - 根据条件打印字符串之间的行
问题描述
我有一个(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,但不搜索include
or 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
# title-of-chunk
# here's some bash code
blah_blah="blah"
推荐阅读
- jestjs - 如何在异步笑话 test.each 案例中传入 done() 参数
- java - 以下划线 (_) 开头的 Hibernate Entity 列名,例如:“_created”和“_updated”作为列名
- node.js - WebStorm 错误:无法安装 Node.js 模块:请指定默认的 Node.js 解释器
- python - Spotify - 使用隐式流获取和更改用户数据
- c - 在c中计算非常大的数字
- html - 如何在 html 文档中生成带有图标的表格。使用 rmarkdown 创建
- javascript - 有什么不同以及为什么在构造函数中需要“this.initialize.apply”
- javascript - Jest SpyOn 值而不是 getter
- google-bigquery - 将嵌套的 customDimension 列数据转置为行 Bigquery
- javascript - jQuery网格不显示结果