Created
April 22, 2025 14:10
-
-
Save mrsarm/a902c2d0bc58d59d430a8868e9104020 to your computer and use it in GitHub Desktop.
replace.sh: replace a given text with another in all matching files.
This file contains hidden or 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
#!/usr/bin/env bash | |
# Check if at least three arguments are provided | |
if [ "$#" -lt 3 ]; then | |
echo "Replace a given text with another in all matching files." | |
echo | |
echo "Usage: replace.sh <glob> <find_text> <replace_text> [--dry-run]" | |
echo | |
echo 'E.g.: replace.sh ".env*" "API_URL=http:\/\/localhost:80\n" "API_URL=http:\/\/localhost:8080\nAPI_VERSION=v2"' | |
exit 1 | |
fi | |
# Assign arguments to variables | |
GLOB=$1 | |
FIND_TEXT=$2 | |
REPLACE_TEXT=$3 | |
DRY_RUN=false | |
# Check for the optional --dry-run argument | |
if [ "$#" -eq 4 ] && [ "$4" == "--dry-run" ]; then | |
DRY_RUN=true | |
fi | |
# Use the glob to find matching files | |
FILES=$(eval "ls $GLOB" 2>/dev/null) | |
# Check if any files matched the glob | |
if [ -z "$FILES" ]; then | |
echo "No files found matching the glob: $GLOB" | |
exit 1 | |
fi | |
# Iterate over each file | |
for FILE in $FILES; do | |
if [ -f "$FILE" ]; then | |
if $DRY_RUN; then | |
# Dry-run: Show what would be replaced | |
echo "Dry-run: will replace \"$FIND_TEXT\" with \"$REPLACE_TEXT\" in $FILE" | |
else | |
# Actual replacement | |
sed -zi "s/$FIND_TEXT/$REPLACE_TEXT/g" "$FILE" | |
echo "Updated $FILE" | |
fi | |
else | |
echo "Skipping $FILE (not a regular file)" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment