Skip to content

Instantly share code, notes, and snippets.

@gabssnake
Created January 20, 2026 20:59
Show Gist options
  • Select an option

  • Save gabssnake/f0e4c32fd7aa720b8bf2e615765d8828 to your computer and use it in GitHub Desktop.

Select an option

Save gabssnake/f0e4c32fd7aa720b8bf2e615765d8828 to your computer and use it in GitHub Desktop.
SQL literate programming
#!/usr/bin/env bash
# Usage:
# ./literate-sql.sh <file.md>
# Credit:
# https://github.com/monacoremo/postgrest-sessions-example/
set -euo pipefail
[[ $# -eq 1 ]] || { echo "Usage: $0 <file.md>" >&2; exit 1; }
[[ -f "$1" ]] || { echo "File not found: $1" >&2; exit 1; }
script=$(cat <<'SED'
#!/usr/bin/env -S sed -f
# This `sed` script turns a Markdown file with SQL code blocks into an SQL file.
# The non-SQL lines are commented out in order to maintain the line numbers.
# This can be useful as error messages with line numbers also apply to the
# original file.
# First, we comment out all lines that do not belong to Markdown code blocks
# that start and end with '```'.
/^```/,/^```/ !s/^/-- /
# Explanation:
# * '/^```/,/^```/' matches all ranges of lines that start and end with lines
# beginning with '```', i.e. the Markdown code blocks in the file.
# * '!' inverts the line selection, so the following command applies to all
# lines that do not belong to Markdown code blocks.
# * 's/^/-- /' replaces the beginning of the line with '-- ', which comments it
# out in SQL.
# We also need to comment out the beginnings and ends of the code blocks.
/^```/ s/^/-- /
# This matches all lines beginning with '```' and prepends '-- ' to them
SED
)
sed -f <(echo "$script") "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment