Using grep with negative look-ahead returning no matches


So I am writing a few scripts for migrating SVN to GIT, we have a bunch of “old” branches in SVN that still exist but don’t need to be moved to GIT. (Branches which happened to have already been merged to trunk).
After a bit of google-fu I’ve come up with the following:

$(git for-each-ref --format='%(refname:short)' --merged origin/trunk | grep '(?!origin\/trunk)origin\/.*')

To be passed to

git branch -D --remote _previouscommandgoeshere_

If I run just git for-each-ref --format='%(refname:short)' --merged origin/trunk I get the following output:

origin/[email protected]
origin/[email protected]

When I add the grep command I get 0 values.

However, has thaught me that my regexp is doing exactly what I want to do. Remove all branches except for the trunk branch.

What is wrong with the regexp/grep? (note I am not a linux/grep guru. This is all done in bash that comes with windows git)


The regexp is right, but grep by default does not support PCRE expression constructs like Negative look-ahead (?!. You need to enable the -P flag to enable the PCRE library, without that it just supports the Basic Regular Expression engine

.. | grep -oP '(?!origin\/trunk)origin\/.*'

Or use a perl regex match on the command line for which no flags need to be set up

.. | perl -ne 'print if /(?!origin\/trunk)origin\/.*/'

Answered By – Inian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published