#!/usr/bin/env bash #!/bin/bash # Check if a directory argument was provided if [ "$#" -ne 1 ]; then echo "Usage: $0 " exit 1 fi SEARCH_DIR="$1" # Validate that the directory exists if [ ! -d "$SEARCH_DIR" ]; then echo "Error: Directory '$SEARCH_DIR' does not exist" exit 1 fi echo "Starting search and replace in directory: $SEARCH_DIR" # Function to process a file process_file() { local file="$1" echo "Processing file: $file" # Create a backup of the original file cp "$file" "${file}.bak" # Use sed to perform the replacements # For three-item pattern: [text1', 'text2', 'text3] -> [[text1]], [[text2]], [[text3]] sed -i -E 's/\[(([^,'\'']*)[^,]*'\''[[:space:]]*,[[:space:]]*'\''([^,'\'']*)[^,]*'\''[[:space:]]*,[[:space:]]*'\''([^,'\'']*)[^]]*)\]/[[\2]], [[\3]], [[\4]]/g' "$file" # For two-item pattern: [text1', 'text2] -> [[text1]], [[text2]] sed -i -E 's/\[(([^,'\'']*)[^,]*'\''[[:space:]]*,[[:space:]]*'\''([^,'\'']*)[^]]*)\]/[[\2]], [[\3]]/g' "$file" # Check if any changes were made if cmp -s "$file" "${file}.bak"; then echo " No changes made to $file" rm "${file}.bak" else echo " Updated $file" fi } # Find all text files recursively and process them find "$SEARCH_DIR" -type f -not -path "*/\.*" | while read -r file; do # Check if file contains the pattern before processing if grep -q "\[.*'.*,.*'.*\]" "$file" 2>/dev/null; then process_file "$file" fi done echo "Search and replace operation completed"