Skip to content

Instantly share code, notes, and snippets.

@decal
Created May 7, 2024 19:47
Show Gist options
  • Save decal/b1d1f0a7c50e431316791291f4ed22b3 to your computer and use it in GitHub Desktop.
Save decal/b1d1f0a7c50e431316791291f4ed22b3 to your computer and use it in GitHub Desktop.
Extract fenced code blocks from markdown into separate files
#!/usr/bin/env ruby
# coding: utf-8
#
# mdunfence - Extract fenced code blocks from markdown into separate files.
#
# All files with the markdown extension under the current working directory are
# handled and the new files will be named after their parent markdown filename
# with a count appended to keep track of multiple extracted code blocks. The
# optional language identifier will be used as the new file extension.
#
# For example, two files hello0.cs and hello1.ext are produced when given a
# markdown file named "hello.md" with the contents below:
#
##*Hello World Examples*
##
##```cs
##Console.WriteLine("Hello World!");
##```
##
##```
##int main(void) {
## puts("Hello World!");
##
## return 0;
##}
##```
#
#
# Written by Derek Callaway <derek.callaway@ioactive.com>
#
Dir.glob('**/*.md').each do |f|
STDOUT.puts(f) if ENV['MDUNFENCE_DEBUG']
aflag, anumb, afile = false, 0, nil
File.readlines(f).each do |l|
if l.start_with?('```')
if !aflag
aflag = true
anext = l.split('`').last
anext = '' if !anext
anext.strip!
if anext.empty?
anext = 'ext'
else
anext.downcase!
anext = 'cs' if anext.eql?('c#') or anext.eql?('csharp')
end
abase = File.basename(f)
aname = abase.split('.').first
afnam = "#{aname}#{anumb}.#{anext}"
anumb += 1
afile = File.open(afnam, 'w')
STDOUT.puts(afnam) if ENV['MDUNFENCE_DEBUG']
STDERR.puts(afile) if ENV['MDUNFENCE_DEBUG']
else
aflag = false
afile.close
end
else
if aflag
afile.write(l)
end
end
end
end
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment