![多行(在一个段落中)模式替换使用 awk 或 sed](https://linux22.com/image/84609/%E5%A4%9A%E8%A1%8C%EF%BC%88%E5%9C%A8%E4%B8%80%E4%B8%AA%E6%AE%B5%E8%90%BD%E4%B8%AD%EF%BC%89%E6%A8%A1%E5%BC%8F%E6%9B%BF%E6%8D%A2%E4%BD%BF%E7%94%A8%20awk%20%E6%88%96%20sed.png)
$cat test.txt
blablabla
```{r}
blabla
```
blablabla
blablabla
blablabla
```{r}
blablabla
blablabla
imname <- "FIGNAME1"
saveflag <- savepdf(imname)
```
```{r}
blablabla
blablabla
imname <- "FIGNAME2"
saveflag <- savepdf(imname)
```
blablabla
我想更换:
\`\`\`{r}** to **\`\`\`{r figname:FIGNAME1}**, where **FIGNAME1** comes from the line start with **imname**, can be match by **imname.\*".\*"**.
预期输出:
blablabla
```{r}
blabla
```
blablabla
blablabla
blablabla
```{r figname:FIGNAME1}
blablabla
blablabla
imname <- "FIGNAME1"
saveflag <- savepdf(imname)
```
```{r figname:FIGNAME2}
blablabla
blablabla
imname <- "FIGNAME2"
saveflag <- savepdf(imname)
```
blablabla
我尝试过sed
但没有成功。
sed -e '/\`\`\`.*r/{:a;N;/^$/p;/imname.*".*"/!{$!ba};s/\`\`\`.*r\(.*imname.*\)"\(.*\)"/```{r figname:\2\1"\2"/}' test.txt
答案1
sed '
/{r}/{ #if line consist {r}
:1 #mark No.1
$!{ #if not last line:
N #append next line
/\n\n/!b1 #if not empty line
} #+return to mark No.1
} #=collect one paragraph(from {r} to empty line)
s/}.*imname <- "\([^"]*\)/ figname:\1&/ #add text after "imname" to "r"
' test.txt