多行(在一个段落中)模式替换使用 awk 或 sed

多行(在一个段落中)模式替换使用 awk 或 sed
$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

相关内容