#!/bin/bash # === CONFIGURATION === OUTPUT="compilation.md" # === ARGUMENTS === if [[ $# -eq 0 ]]; then TARGET_DIR="." echo "Aucun dossier → dossier courant : $PWD" elif [[ $# -eq 1 ]]; then TARGET_DIR="$1" if [[ ! -d "$TARGET_DIR" ]]; then echo "Erreur : dossier '$TARGET_DIR' introuvable." >&2 exit 1 fi else echo "Usage: $0 [dossier]" >&2 exit 1 fi # Chemin absolu TARGET_DIR="$(cd "$TARGET_DIR" && pwd)" OUTPUT_PATH="$TARGET_DIR/$OUTPUT" # Vider le fichier > "$OUTPUT_PATH" echo "Regroupement dans : $TARGET_DIR" echo "Sortie → $OUTPUT_PATH" echo "--------------------------------------------------" # === BOUCLE SANS PIPE (clé du succès) === while IFS= read -r -d '' file; do [[ "$file" == "$OUTPUT_PATH" ]] && continue rel_path="${file#$TARGET_DIR/}" echo "Traitement : $rel_path" # --- Titre depuis # Premier --- title_line=$(grep -m 1 "^[[:space:]]*#[[:space:]]*" "$file") if [[ -n "$title_line" ]]; then title=$(echo "$title_line" | sed 's/^[[:space:]]*#[[:space:]]*\(.*\)/\1/' | xargs) content_start=2 # Ignorer si aucun contenu après le titre (que des blancs ou rien) if ! tail -n +"$content_start" "$file" | grep -q '[^[:space:]]'; then echo "Ignoré (titre sans contenu) : $rel_path" continue fi else # --- Sinon : nom du fichier --- title=$(basename "$file" .md) title=$(echo "$title" | sed 's/[-_]/ /g') # Majuscule première lettre (macOS compatible) title="$(echo "$title" | awk '{print toupper(substr($0,1,1)) substr($0,2)}')" content_start=1 fi # --- Ajout au fichier --- printf "\n# %s\n\n" "$title" >> "$OUTPUT_PATH" tail -n +"$content_start" "$file" >> "$OUTPUT_PATH" printf "\n" >> "$OUTPUT_PATH" done < <(find "$TARGET_DIR" -type f -name "*.md" ! -name "$OUTPUT" -not -empty -print0 | sort -z) echo "--------------------------------------------------" echo "TERMINE : $OUTPUT_PATH"