split Md file by headings into multiple files

# mkw - split mmd file by heading

#!/bin/bash

csplit -s -f chapter --suffix-format="%d.md" *.mmd '/# /' "{*}"
# Create a dir to place mmd files -p to check if exists. Move mmd file to then grab headings to rename filename
mkdir -p mmdorig
mv *.mmd mmdorig/

#set -eux

for file in *
do
   # No renaming directories!
  if [ -f "$file" ]
   then
       newname=`head -1 $file`
       if [ -f "$newname" ]
       then
              echo "Cannot rename $file to $newname - keep this file"
       else
              mv "$file" "$newname".md
       fi
  fi
done

# grep pattern clean up the spaces and #
pattern="# " # removing #

# mkw: this can be used to clean up filenames by MS Windows users or users leaving spaces in filenames... YW! 🙂
# create an array of filenames and split on newlines

IFS=$'\n'
tmp=($(ls | grep ${pattern}))
unset IFS

# for each filename
for filename in "${tmp[@]}"; do

    # rename the filename to use "" rather than "# "

    mv -v "${filename}" "${filename//# /}"
done

pattern=" " # removing spaces from the first line to use in filename

# see notes above - just another invocation

IFS=$'\n'
tmp=($(ls | grep ${pattern}))
unset IFS

# for each filename

for filename in "${tmp[@]}"; do

    # rename the filename to use "" rather than " "

    mv -v "${filename}" "${filename// /}"
done