File size: 722 Bytes
4a0fadb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash

# 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"