Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep with negative look-ahead returning no matches

Tags:

git

regex

grep

bash

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/IR1091
origin/IR1102
origin/IR1105
...
origin/IR932
origin/Software
origin/trunk
origin/trunk@6792
origin/trunk@6850

When I add the grep command I get 0 values.

However, https://regexr.com/3ot1t 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)

like image 602
Daan Timmer Avatar asked Sep 19 '25 05:09

Daan Timmer


1 Answers

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\/.*/'
like image 141
Inian Avatar answered Sep 21 '25 17:09

Inian