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

관련 정보