Skip to content

Instantly share code, notes, and snippets.

@BrainWart
Last active June 7, 2022 11:33
Show Gist options
  • Save BrainWart/bcad8407e65805daa9e614656e6a1717 to your computer and use it in GitHub Desktop.
Save BrainWart/bcad8407e65805daa9e614656e6a1717 to your computer and use it in GitHub Desktop.
This script will take the markdown files in a folder, allow you to order them, and then it will replace the file links with the chapter number.
#!/bin/bash
# Create a temporary directory for storing files
TMP=$(mktemp -d -t tmp.XXXXXXXXX)
function finish {
rm -rf $TMP
}
trap finish EXIT
if [ -z "$1" ]; then echo "Arg 1 must be a directory path"; exit; fi
pushd $1 > /dev/null
PWDIR=$1
shift
# Build a list of files to be included in the book
find . -name "*.md" | xargs -l1 basename > "$TMP/order.txt"
${EDITOR:-vim} "$TMP/order.txt" || exit 1
# Generate a list of substitute commands for sed
nl --number-width=3 --number-format=rz < "$TMP/order.txt" | awk '{ print "s/]("$2"/](ch"$1".xhtml/g" }' > "$TMP/commands.txt"
# Copy the files to the temp dir and modify them
mkdir "$TMP/files"
xargs -a "$TMP/order.txt" -i cp {} $TMP/files/{}
xargs -a "$TMP/order.txt" -i sed --file="$TMP/commands.txt" -i $TMP/files/{}
# Go back to the original directory for saving the final file
popd > /dev/null
# Build the list of files for pandoc and pass them along to pandoc while also passing the resource directory and any other arguments
awk "{ print \"$TMP/files/\"\$1 }" < "$TMP/order.txt" | xargs pandoc --resource-path="$PWDIR" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment