Skip to content

Instantly share code, notes, and snippets.

@gwpl
Last active February 26, 2025 11:27
Show Gist options
  • Save gwpl/8006aad209b84b0f618b45490948a044 to your computer and use it in GitHub Desktop.
Save gwpl/8006aad209b84b0f618b45490948a044 to your computer and use it in GitHub Desktop.
fix_markdown_urls - `# Fixg URLs in markdown to be surrounded by <...>`
#!/bin/bash
# Fixg URLs in markdown to be surrounded by <...>
# https://gist.github.com/gwpl/8006aad209b84b0f618b45490948a044
function usage() {
echo "Usage: $0 [-h|--help] [-i|--in-place] [file]"
echo " -h, --help Show this help message and exit"
echo " -i, --in-place Edit files in place"
echo " file File to process (use '-' for standard input)"
}
function fix_markdown_urls() {
# Let's keep previouss perl verision in comment, just in case user needs to switch from python to perl oneliners:
# $ perl -pe 's/(?<!<)(https?:\/\/[^\s()<>\[\]]+)(?!>)/<$1>/g'
python -c "import re, sys; sys.stdout.write(re.sub(r'(?<!<)(https?://[^\s()<>[\]]+)(?!>)', r'<\\1>', sys.stdin.read()))"
}
IN_PLACE=false
FILE="-"
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
usage
exit 0
;;
-i|--in-place)
IN_PLACE=true
shift
;;
-*)
echo "Unknown option: $1"
usage
exit 1
;;
*)
FILE="$1"
shift
;;
esac
done
if $IN_PLACE; then
if [[ "$FILE" == "-" ]]; then
echo "Cannot use in-place editing with standard input"
exit 1
fi
TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"' EXIT
fix_markdown_urls < "$FILE" > "$TMPFILE"
cat "$TMPFILE" > "$FILE"
else
if [[ "$FILE" == "-" ]]; then
fix_markdown_urls
else
fix_markdown_urls < "$FILE"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment