Git: delete all remote branches with a certain pattern

I would like to execute a single command which deletes branches on the remote that follow a certain pattern.

Example use case:
Delete all branches on origin that begin with v1/.

If possible, it would be nice to enhance this command with a safety check: only delete branches which have been merged into master.


To list such branches :

git for-each-ref --merged master \
   --format="%(refname:short)" refs/remotes/origin/v1

# if you want only the `v1/xxx` part without the leading `origin/` :
git for-each-ref --merged master \
    --format="%(refname:lstrip=3)" refs/remotes/origin/v1

You can then feed its output to git push origin -d :

git for-each-ref --merged master \
    --format="%(refname:lstrip=3)" refs/remotes/origin/v1 |\
    xargs git push origin -d

note : the syntax to use git for-each-ref is a bit more intricate than the one for git branch, but its output is stable, highly configurable with the --format option and suitable for scripting. git branch is intended for human reading and has several formatting options which make for annoying bugs in scripts (leading * on the active branch, non configurable specific spacing ...)

for reference, the equivalent command using git branch would be :

git branch --merged master -r --list origin/v1