Skip to content

Instantly share code, notes, and snippets.

@oddevan
Created August 9, 2024 18:46
Show Gist options
  • Save oddevan/e51c2283c6d27dedd77c7484facf820d to your computer and use it in GitHub Desktop.
Save oddevan/e51c2283c6d27dedd77c7484facf820d to your computer and use it in GitHub Desktop.
Break a single markdown file up by horizontal lines (either --- or ***). I use this to move a draft from writing (all in one file) to editing (scenes as separate files).
#!/opt/homebrew/bin/php
<?php
if (!isset($argv[1])) {
echo "Need to supply a file!";
die(1);
}
$source_file_path = str_starts_with($argv[1], DIRECTORY_SEPARATOR) ? $argv[1] : getcwd() . DIRECTORY_SEPARATOR . $argv[1];
$destination_dir = isset($argv[2]) ? (
rtrim(
str_starts_with($argv[2], DIRECTORY_SEPARATOR) ? $argv[2] : getcwd() . DIRECTORY_SEPARATOR . $argv[2],
DIRECTORY_SEPARATOR
) . DIRECTORY_SEPARATOR
) : getcwd() . DIRECTORY_SEPARATOR;
$destination_file_base = $destination_dir . basename($source_file_path, '.md');
$scratch = '';
$count = 0;
$handle = fopen($source_file_path, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (str_starts_with($line, '---') || str_starts_with($line, '***')) {
$count += 1;
$fname = $destination_file_base . str_pad($count, 3, '0', STR_PAD_LEFT) . '.md';
file_put_contents($fname, $scratch);
fgets($handle); // Burn the next newline
$scratch = ''; // Reset $scratch
} else {
$scratch .= $line;
}
}
fclose($handle);
// Write the last file
$count += 1;
$fname = $destination_file_base . str_pad($count, 3, '0', STR_PAD_LEFT) . '.md';
file_put_contents($fname, $scratch);
}
echo "Wrote $count files to $destination_dir.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment