Skip to content

Instantly share code, notes, and snippets.

@chipotle
Created May 12, 2022 15:53
Show Gist options
  • Save chipotle/a83229cacfa42af61674dc5b64e0c9e8 to your computer and use it in GitHub Desktop.
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
#!/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
@chipotle
Copy link
Author

This script splits a file into multiple pieces using # Markdown headers as the split points and the filenames:

# file1.foobar.md
Lorem ipsum blah blah blah
# file2.foobar.md
Lorem ipsum etc so on and so forth

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment