Remove SQL comments in SQL scripts
I often want to provide SQL structure dumps as context for AI assisted development. But most of the dumps tools provide SQL scripts with comments. I do not want to provide them to the AI. So, I need to strip the comments. This is the file I use:
#!/bin/bash
# 1. Check if an input file was provided
if [ "$#" -lt 1 ]; then
echo "Usage: $0 [output_file.sql]"
exit 1
fi
INPUT_FILE="$1"
OUTPUT_FILE="${2:-cleaned_$1}"
# 2. Check if input file exists
if [ ! -f "$INPUT_FILE" ]; then
echo "Error: File '$INPUT_FILE' not found!"
exit 1
fi
# 3. Create secure temporary files for the intermediate passes
PASS1_FILE=$(mktemp)
PASS2_FILE=$(mktemp)
# Set a trap to automatically delete the temporary files when the script finishes or is aborted
trap 'rm -f "$PASS1_FILE" "$PASS2_FILE"' EXIT
echo "Starting multi-pass SQL cleanup on '$INPUT_FILE'..."
# ==============================================================================
# PASS 1: Remove Standard Comments
# ==============================================================================
echo " -> Pass 1: Removing standard '--' comments..."
# Looks for lines starting with '--' (ignoring leading spaces) and deletes them.
sed '/^[[:space:]]*--/d' "$INPUT_FILE" > "$PASS1_FILE"
# ==============================================================================
# PASS 2: Remove Conditional Execution Comments
# ==============================================================================
echo " -> Pass 2: Removing conditional '/*! ... */' comments..."
# Looks for lines starting with '/*' (ignoring leading spaces) and deletes them.
sed '/^[[:space:]]*\/\*/d' "$PASS1_FILE" > "$PASS2_FILE"
# ==============================================================================
# PASS 3: Clean Up Empty Lines
# ==============================================================================
echo " -> Pass 3: Removing blank lines left behind..."
# Looks for lines that are entirely empty or contain only whitespace and deletes them.
sed '/^[[:space:]]*$/d' "$PASS2_FILE" > "$OUTPUT_FILE"
# ==============================================================================
# FINISH
# ==============================================================================
echo "Done! Cleaned SQL saved to: $OUTPUT_FILE"