Skip to content

Instantly share code, notes, and snippets.

@renkin
Created July 8, 2023 05:31
Show Gist options
  • Save renkin/80ce11f52de8bddcc8313aefc4458c9a to your computer and use it in GitHub Desktop.
Save renkin/80ce11f52de8bddcc8313aefc4458c9a to your computer and use it in GitHub Desktop.
Script to replace a list of regex search patterns within a directory structure
#!/bin/bash
# Parameters
BASE_DIRECTORY='ToReplace'
FILE_PATTERN='*Controller.java'
# Perform find and replace operation for given search and replacement patterns
perform_replace() {
local SEARCH_PATTERN=$1
local REPLACEMENT_PATTERN=$2
local file=$3
SEARCH_PATTERN_HITS=$(grep -c -E "$SEARCH_PATTERN" "$file")
echo "- $SEARCH_PATTERN_HITS time(s) replaced $SEARCH_PATTERN with $REPLACEMENT_PATTERN"
sed -r -i "s/$SEARCH_PATTERN/$REPLACEMENT_PATTERN/g" "$file"
# sed --debug -r -i "s/$SEARCH_PATTERN/$REPLACEMENT_PATTERN/g" "$file"
}
# Find all files in a directory (recursively) that match a specific pattern
files=$(find $BASE_DIRECTORY -type f -name $FILE_PATTERN)
# Iterate over each file and perform the find and replace operation for each pattern pair
# Matching groups are written as \1 not $1 (sed syntax)
echo ""
for file in $files; do
echo "Processing file $file ..."
perform_replace 'SimpleSearchPattern' 'SimpleReplacement' "$file"
perform_replace 'SearchPatternWithBracketsAndMatchingGroup\((.+)\)' 'ReplacementWithBracketsAndMatchingGroup(matchingGroup = \1)' "$file"
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment