← Back to context

Comment by oulipo

9 days ago

I'm using this quickly put-together shell script called replace

    #!/usr/bin/env bash
    
    # Function to escape special characters for sed
    escape_sed_string() {
        printf '%s\n' "$1" | gsed -e 's/[]\/$*.^[]/\\&/g'
    }
    
    help() {
      gum style --foreground cyan --italic "\
    Usage (everything optional, you will be prompted):\n\
    $0\n\
      --ext .js --ext .ts\n\
      --from \"source string\"\n\
      --to \"replacement string\"\n\
      --dir somePath"
    }
    
    # Parse command line arguments
    while [[ "$#" -gt 0 ]]; do
        case $1 in
            -h)
                help
                exit 0
                ;;
            --help)
                help
                exit 0
                ;;
            --ext) EXTENSIONS+=("$2"); shift ;;
            --from) REPLACE_FROM="$2"; shift ;;
            --to) REPLACE_TO="$2"; shift ;;
            --dir) DIRECTORY="$2"; shift ;;
            *) gum style --foreground red --bold "Unknown parameter: $1"; exit 1 ;;
        esac
        shift
    done
    
    # Check for missing parameters and prompt using gum
    if [ -z "${EXTENSIONS+set}" ]; then
        EXTENSIONS=($(gum choose \
            --no-limit \
            --selected .ts,.mts,.tsx,.vue,.js,.cjs,.mjs \
            .ts .mts .tsx .vue .js .cjs .mjs .txt .md .html .json))
    fi
    
    # Exit if no extension is selected
    if [ ${#EXTENSIONS[@]} -eq 0 ]; then
        gum style --foreground red --bold " Error: No extensions selected. Exiting."
        exit 1
    fi
    
    if [ -z "${REPLACE_FROM+set}" ]; then
        REPLACE_FROM=$(gum input --placeholder "Search string:")
        if [ -z "${REPLACE_FROM}" ]; then
            echo "No replace from string, exiting"
            exit 1
        fi
    fi
    if [ -z "${REPLACE_TO+set}" ]; then
        REPLACE_TO=$(gum input --placeholder "Replace string:")
    fi
    if [ -z "${DIRECTORY+set}" ]; then
        DIRECTORY="."
    fi
    
    # Escape strings for sed
    ESCAPED_FROM=$(escape_sed_string "$REPLACE_FROM")
    ESCAPED_TO=$(escape_sed_string "$REPLACE_TO")
    
    # Run the replacement
    for ext in "${EXTENSIONS[@]}"; do
        gum style --foreground blue " Replacing ${ext} files..."
        find "$DIRECTORY" -type f -name "*$ext" ! -path "*/node_modules/*" -exec gsed -i "s/$ESCAPED_FROM/$ESCAPED_TO/g" {} \;
    done
    
    gum style --foreground green --bold " Replacement complete."