2
$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

I want to replace:

\`\`\`{r}** to **\`\`\`{r figname:FIGNAME1}**, where **FIGNAME1** comes from the line start with **imname**, can be match by **imname.\*".\*"**.

Expected output:

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

I tried sed but no success.

sed -e '/\`\`\`.*r/{:a;N;/^$/p;/imname.*".*"/!{$!ba};s/\`\`\`.*r\(.*imname.*\)"\(.*\)"/```{r figname:\2\1"\2"/}' test.txt
  • What of sed did you try? – tachomi Mar 1 '16 at 16:36
  • The sed script match the pattern across over paragraph as well, which is not expect. – Ming Su Mar 1 '16 at 16:40
  • 1
    Any reason you can't use Perl? You can redefine line-end and get some nice multi-line matching with perl -p0. – Toby Speight Mar 1 '16 at 17:33
3
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
  • Thank you. It works very well. Could you please explan little bit on your code? – Ming Su Mar 2 '16 at 1:04
  • @MingSu See commented. – Costas Mar 2 '16 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.