首页 > 解决方案 > 将 grep 与负前瞻一起使用,不返回任何匹配项

问题描述

所以我正在编写一些将 SVN 迁移到 GIT 的脚本,我们在 SVN 中有一堆“旧”分支,它们仍然存在但不需要迁移到 GIT。(碰巧已经合并到主干的分支)。经过一番google-fu后,我想出了以下内容:

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

被传递给

git branch -D --remote _previouscommandgoeshere_

如果我只运行,git for-each-ref --format='%(refname:short)' --merged origin/trunk我会得到以下输出:

origin/IR1091
origin/IR1102
origin/IR1105
...
origin/IR932
origin/Software
origin/trunk
origin/trunk@6792
origin/trunk@6850

当我添加grep命令时,我得到 0 个值。

但是,https: //regexr.com/3ot1t 告诉我我的正则表达式正在做我想做的事情。删除除分支之外的所有trunk分支。

正则表达式/grep 有什么问题?(注意我不是linux/grep 大师。这一切都是在 windows git 附带的 bash 中完成的)

标签: regexbashgitgrep

解决方案


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\/.*/'

推荐阅读