| # Usage: ./replace_in_file.sh <file> <search_string> <replace_string> | |
| # --- Input arguments --- | |
| FILE="$1" | |
| SEARCH="$2" | |
| REPLACE="$3" | |
| # --- Sanity checks --- | |
| if [[ $# -ne 3 ]]; then | |
| echo "Usage: $0 <file> <search_string> <replace_string>" | |
| exit 1 | |
| fi | |
| if [[ ! -f "$FILE" ]]; then | |
| echo "Error: File '$FILE' not found!" | |
| exit 1 | |
| fi | |
| # --- Create a temporary file --- | |
| TMP_FILE=$(mktemp) | |
| # --- Replace all occurrences using sed --- | |
| # The '|' delimiter avoids conflicts with slashes in strings. | |
| sed "s|$SEARCH|$REPLACE|g" "$FILE" > "$TMP_FILE" | |
| # --- Move the temp file back to original (atomic replace) --- | |
| mv "$TMP_FILE" "$FILE" | |
| echo "Replaced all occurrences of '$SEARCH' with '$REPLACE' in $FILE" | |