Skip to content

Instantly share code, notes, and snippets.

@iwconfig
Created May 3, 2024 20:38
Show Gist options
  • Save iwconfig/066bfee75c2b256fd8bf73067fe85c13 to your computer and use it in GitHub Desktop.
Save iwconfig/066bfee75c2b256fd8bf73067fe85c13 to your computer and use it in GitHub Desktop.
Replace text, e.g. secrets, in all files in all git commits using `git filter-branch` and `sed`.

Replace text, e.g. secrets, in all files in all git commits using git filter-branch and sed.

a. Download replace-text.sh

b. Clone the gist repo in the same directory as replace-text.sh

  • using SSH url:

    1. git clone git@gist.github.com:<reponame (hash)>
  • using HTTPS url:

    1. git clone https://gist.github.com/<username>/<reponame (hash)>
    2. git remote set-url --add origin git@gist.github.com:<reponame (hash)>
    3. git remote set-url --delete origin https://gist.github.com/<username>/<reponame (hash)>

c. cd into the gist repo directory

d. run replace-text.sh on all commits

  • git filter-branch -f --tree-filter 'bash ../replace-text.sh <string> <my_string>' -- --all

e. restore dates

  • git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"'

f. Optional: remove dangling commits

  1. git reflog expire --expire-unreachable=now --all
  2. git gc --prune=now

g. Force push to remote repo

  1. git push -f
function echo() {
builtin echo ${GIT_COMMIT:0:6}: "$@"
}
builtin echo
echo replacing "\"$1\"" to "\"$2\""
for f in $(git ls-tree --full-tree -r --name-only $GIT_COMMIT); do
echo saving modification timestamp of "$f"
touch -r "$f" "$f".timestamp
echo modifying "$f"
sed -i "s/$1/$2/g" "$f"
echo restoring original modification timestamp of "$f"
touch -r "$f".timestamp "$f"
echo removing "$f".timestamp
rm "$f".timestamp
done
builtin echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment