Using sed to Update Markdown Headers
I’m in the process of migrating an existing set of markdown documents to an internal Docusaurus blog. The markdown-to-html rendering with Docusaurus has proved decidedly less forgiving than our existing renderer, so I’ve been running the markdown files through some tweaks to get things to display correctly. One item that caused me to work a little harder than normal involved headings: if the heading lacks a space between the octothorpes and the heading text, Docusaurus renders it as normal text, like this:
###My Heading
I know my way around sed
via Google, so I thought I’d find a quick fix. It took me several iterations of sed
and git reset --hard
, though, to arrive at this:
$ find . -name '*.md' -exec sed -E -i 's/^(#+)([^# ])/\1 \2/g' {} \;
Things I learned:
- Using back-references in
sed
requires extended regular expressions (-E
) — my forays with-e
resulted insed: -e expression #1, char 1: unknown command: `-'
- My attempts using
\s
instead of a literal space, to not match lines with a space after the last octothorpe, didn’t work — they matched both “###My Heading” and “### My Heading”. The latter would result in two spaces between the octothorpe and title. I don’t understand that one.