Created
May 12, 2022 15:53
-
-
Save chipotle/a83229cacfa42af61674dc5b64e0c9e8 to your computer and use it in GitHub Desktop.
Ruby script to split one file into multiple files, using Markdown h1 headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
if ARGV.empty? | |
puts "Usage: #{__FILE__} filename [directory]\n\n" | |
puts "The file 'filename' will be split at each Markdown h1 ('# ') header. If" | |
puts "'directory' is specified, it will be used as the output directory." | |
puts "Otherwise files will be written to the current directory.\n\n" | |
exit(2) | |
end | |
out_dir = ARGV[1] || '.' | |
out_files = {} | |
out_file = "" | |
puts "Writing to directory #{out_dir}" | |
f = File.open(ARGV[0]) | |
f.each_line do |l| | |
if l[0,2] == "# " | |
out_file = l[2, 99] | |
print "--> #{out_file}" | |
out_files[out_file] = "" | |
elsif out_file != "" | |
out_files[out_file] << l | |
end | |
end | |
out_files.each do |filename, body| | |
IO.write(out_dir + "/" + filename.strip, body.lstrip) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script splits a file into multiple pieces using
#
Markdown headers as the split points and the filenames:This is useful if you have some reason to create a whole bunch of short files all at once. I wrote it for a specific need in documentation, but have also used it for creating BBEdit clippings.