Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - Rename multiple branches

Tags:

git

bash

Here we have a git repo which has multiple branches which start with the same prefix just like this:

pfx.branchName1  
pfx.branchName2  
pfx.branchName3  
...

So the question is how to quickly remove all the prefixes ("pfx.") from all the branches and get something like this:

branchName1  
branchName2  
branchName3  
... 
like image 756
Just Shadow Avatar asked Jul 15 '17 12:07

Just Shadow


People also ask

Can you rename branches git?

The steps to change a git branch name are: Rename the Git branch locally with the git branch -m new-branch-name command. Push the new branch to your GitHub or GitLab repo. Delete the branch with the old name from your remote repo.


1 Answers

Found an universal command that searches for the branches which contain our desired string (e.g. "StringToFind") and renames by replacing that part with the string we want (e.g. "ReplaceWith"):

git branch | grep "StringToFind" | awk '{original=$1; sub("StringToFind","ReplaceWith"); print original, $1}' | xargs -n 2 git branch -m

Note: Before starting renaming we can run this command to see which branches are going to be renamed (just for convenience):

git branch | grep "StringToFind" | awk '{original=$1; sub("StringToFind","ReplaceWith"); print original, "->" , $1}'  

So, for our case, use this for removing prefix:

git branch | grep "pfx." | awk '{original=$1; sub("pfx.",""); print original, $1}' | xargs -n 2 git branch -m  

And this, for checking before removing:

git branch | grep "pfx." | awk '{original=$1; sub("pfx.",""); print original, "->", $1}'
like image 163
Just Shadow Avatar answered Oct 17 '22 14:10

Just Shadow