Maik Lowrey
Maik Lowrey

Reputation: 17586

How to remove branches except for development and main

Goal Delete all branches except for several exceptions. In my case: development, main

I found this command but it only applies to main.

git branch | grep -v "main" | xargs git branch -D

I thought you could do it like this:

git branch | grep -v "main|development" | xargs git branch -D

But that doesn't work.

Upvotes: 1

Views: 142

Answers (2)

KrassVerpeilt
KrassVerpeilt

Reputation: 445

Escape the Pipe in your pattern \|. Like that:

git branch | grep -v "branchName1\|branchName2\|branchName3" | xargs git branch -D

git branch | grep -v -E "branchName1|branchName2|branchName3" | xargs git branch -D

Short explanation of the parameters

-v or --invert-match The -v parameter returns all non-matching lines, which is important because you want to remove them.

-E or --extended-regexp Means that the pattern which you pass is extended regex which is used for the search. Then you can use the pipe to separate without escaping.

Upvotes: 3

chepner
chepner

Reputation: 532053

Basic regular expressions require you to escape the |, which is otherwise treated as a literal character, to indicate alternation.

git branch | grep -v "main\|development"

If your version of grep supports it, you can use extended regular expression, in which | is the alternation operator.

git branch | grep -Ev "main|development"

Upvotes: 2

Related Questions