Last active
May 20, 2024 13:55
-
-
Save ahmu83/47a9efa03f8197c3ff6e2f6964d97ac4 to your computer and use it in GitHub Desktop.
A Bash script designed to automate the search and replacement of strings in SQL files (or any large text file)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# USAGE: | |
# sh bulk-search-replace.sh dbfile.sql | |
# OR | |
# chmod +x bulk-search-replace.sh | |
# ./bulk-search-replace.sh dbfile.sql | |
# | |
# sed or gsed | |
# | |
# update the search_replace array with the | |
# strings to search and replace before running the script | |
# | |
# Check if a file name is provided as an argument | |
if [ "$#" -ne 1 ]; then | |
echo "Usage: $0 <filename>" | |
exit 1 | |
fi | |
# Assign the file name to a variable | |
FILE=$1 | |
# Check if the file exists | |
if [ ! -f "$FILE" ]; then | |
echo "Error: File does not exist." | |
exit 1 | |
fi | |
# Declare parallel arrays for search and replace terms | |
search=( | |
"bhh_" | |
"https://www.mywebsite.com/media" | |
"https://www.mywebsite.com" | |
) | |
replace=( | |
"wp_12_" | |
"https://mywebsite.wp.test.com/wp-content/uploads/sites/12" | |
"https://mywebsite.wp.test.com" | |
) | |
# Loop through the arrays | |
for i in "${!search[@]}"; do | |
# Use sed to replace each string, with '|' as the delimiter | |
sed -i '' "s|${search[i]}|${replace[i]}|g" "$FILE" | |
done | |
echo "Replacement done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A Bash script designed to automate the search and replacement of strings in SQL files (or any large text file). This script efficiently processes a specified file, utilizing parallel arrays to define multiple replacements.
It’s particularly useful for database migrations or bulk updates, ensuring consistency across database dumps.
The script leverages the sed command-line tool for efficient text processing.
Usage Instructions:
Update the search & replace arrays with parallel search and replace values. Once updated, run the script using the two options below.
sh bulk-search-replace.sh dbfile.sql
OR
chmod +x bulk-search-replace.sh
./bulk-search-replace.sh dbfile.sql