Using bash to find text between strings and replace text in found string

Viewed 74

I have a(n R Markdown) script that contains plain text, plus delimited chunks of bash code that look like this:

```{bash, title-of-chunk, other=TRUE, options=FALSE}
# here's some bash code
blah_blah="blah"
```

I would like to extract all of the bash code chunks into a separate document. The rub is that I would like the different code chunks to be labeled by a comment title-of-chunk. So the result would look like

# title-of-chunk
# here's some bash code
blah_blah="blah"

The chunk title will always be between the first two .'s. I've been working with sed, but haven't found the right combination yet.

2 Answers
awk '$0 ~ /^```$/ {p=0} 
     $1 ~ /^```{bash/ {p=1; print "\n# " substr($2,1,length($2)-1); next}
     p' file >  output

I have extended your sample input:

> cat file
blah blah

```{bash, title-of-chunk, other=TRUE, options=FALSE}
# here's some bash code
blah_blah="blah"
```
blah
blah

```{python, test}
# here's some python code
blah_blah="blah"
```

test

```{bash, exit, other=TRUE, options=FALSE}
# here's some bash code
exit 0
```

Output:

> cat output

# title-of-chunk
# here's some bash code
blah_blah="blah"

# exit
# here's some bash code
exit 0

Based on shown samples only, could you please try following once. Written and tested on site https://ideone.com/iybsWx

awk '
/^```/{
  found=""
}
match($0,/^```{.*title-of-chunk/){
   val=substr($0,RSTART,RLENGTH)
   sub(/.*title/,"title",val)
   print "#"val
   val=""
   found=1
   next
}
found
'  Input_file

Explanation: Adding detailed explanation for above.

awk '                                       ##Starting awk program from here.
/^```/{                                     ##Checking condition if line has ``` then do following.
  found=""                                  ##Nullify found here.
}
match($0,/^```{.*title-of-chunk/){          ##Using match function to match ```{bash till title-of-chunk then do following.
   val=substr($0,RSTART,RLENGTH)            ##Sub-string of matched regex output is being saved in variable here.
   sub(/.*title/,"title",val)               ##Substituting everything till title with title in in val.
   print "#"val                             ##Printing # and val here.
   val=""                                   ##Nullifying val here.
   found=1                                  ##Setting found to 1 here.
   next                                     ##next will skip all further statements from here.
}
found                                       ##Checking condition if found is SET then print the current line.
'  Input_file                               ##Mentioning Input_file name here.
Related