This posting shows how to use a simple bash script to separate a single markdown chunk into separate files named according to each’s slugified heading.

Each heading is defined using ##. So given some markdown text like this (saved to a file e.g. “src.md”):

# Javascript oneliners

## Check if multiple objects are equal

```javascript
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));
// Examples
isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
isEqual({ foo: 'bar' }, { bar: 'foo' }); // false
```

## Get selected text

```javascript
const getSelectedText = () => window.getSelection().toString()
```

## Sort an object by its properties

```javascript
const sort = (obj) =>
Object.keys(obj)
.sort()
.reduce((p, c) => ((p[c] = obj[c]), p), {});
// Example
const colors = {
white: '#ffffff',
black: '#000000',
red: '#ff0000',
green: '#008000',
blue: '#0000ff',
};
sort(colors);
/*
{
black: '#000000',
blue: '#0000ff',
green: '#008000',
red: '#ff0000',
white: '#ffffff',
}
*/
```

## Check if an object is a Promise

```javascript
const isPromise = (obj) =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
```

## Check if an object is an array

```javascript
const isArray = (obj) => Array.isArray(obj);
```

Then using the following bash script (e.g. saved as “chop_into_md.sh”):

#!/usr/bin/env bash

## Recommendation: run this script in a freshly created temp directory
## since this script will potentially overwrite existing .md files. 

slugify() {
       echo "$1" | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | tr A-Z a-z
}

FILE="$1"
CATEG="$2"
[ -e "$FILE" ] || { echo "File $FILE does not exist"; exit 1; }

hdr=""
neu=""
file=""
while read -r line; do
	neu=""
	[[ "$line" =~ ^##' '+(.+) ]] && { hdr="${BASH_REMATCH[1]}"; neu="1"; }
	file="$(slugify "$hdr")"".md"
	topmatter="---\nlayout: page_collection\npage_title: $hdr\ntitle: $hdr\ncategories: $CATEG\n---\n\n"
	[ -z "$neu" ] || echo -e "$topmatter" | tee "$file"
	echo "$line" | tee -a "$file"
done <"$FILE"

And finally running the script on the commandline as follows with the following arguments

  • source file as first argument; and
  • category (or categories in quotes) as 2nd:
./chop_into_md.sh src.md "javascript"

will generate a bunch of .md files:

check-if-an-object-is-an-array.md
check-if-an-object-is-a-promise.md
check-if-multiple-objects-are-equal.md
get-selected-text.md
sort-an-object-by-its-properties.md