#!/bin/sh # Path to your .bib file BIBFILE="assets/library.bib" # Step 1: Extract all citation keys from the .bib file # This assumes keys follow immediately after @...{KEY, bibkeys=$(grep -oP '^@\w+\{\K[^,]+' "$BIBFILE") # Step 2: Initialize array for unused keys unused=() for key in $bibkeys; do if ! grep -qr "$key" . --include="*.qmd"; then unused+=("$key") fi done if [ ${#unused[@]} -eq 0 ]; then echo "All citation keys are used." else echo "Unused citation keys:" for key in "${unused[@]}"; do echo " $key" done fi # Step 5: Optional removal if [ ${#unused[@]} -gt 0 ]; then echo "Removing unused entries from $BIBFILE..." awk -v keys="${unused[*]}" ' BEGIN { split(keys, klist); for (i in klist) unused[klist[i]] = 1; skip = 0; } /^[[:space:]]*@/ { match($0, /^@\w+\{([^,]+),/, m); if (m[1] && unused[m[1]]) { skip = 1; next; } } skip && /^\s*}/ { skip = 0; next; } !skip ' "$BIBFILE" > "$BIBFILE.tmp" && mv "$BIBFILE.tmp" "$BIBFILE" echo "Done." fi