Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a pandoc markdown file which has a lot of code. I want to extract all the code bits from file preferably using sed. The syntax of code in pandoc is three or more ` signs to start and finish the code segment.

```

Code is here

```

I can extract one line but I have no way of extracting between markers.

share|improve this question
add comment

2 Answers

sed -n '/^```/,/^```/ p' < input.file

Will print all lines between ``` but including the ``` lines too. To get rid of that:

sed -n '/^```/,/^```/ p' < input.file | sed '/^```/ d'

You can find an explanation of how to use line ranges by pattern, and the 'p' and 'd' commands starting here:

http://www.grymoire.com/Unix/Sed.html#uh-29

share|improve this answer
add comment

You can also use perl:

perl -0777e '$_=<>;print $1 while /^`{3,}\s*\n(.*?)^`{3,}\s*\n/msg' your_file

Explanation

  • The 0777 part sets the input record separator ($/) to slurp the whole file
  • The regex looks for a line starting with 3 or more backticks then matches and captures as few lines as possible (guaranteed by the lazy quantifier *?) followed by a line starting with 3 or more ticks.
  • The regex modifier m ensures that ^ would match beginning of lines not just the start of the file. The modifier s makes sure that . will match a newline character so that .*? can match several lines. Finally g makes sure that the regex will be applied iteratively to the file contents so that all matches are found.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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