使用egrep正则表达式捕获部分行

时间:2011-10-21 18:18:02

标签: regex bash

我正在尝试通过bash脚本提交git补丁。这不是一个git问题!这是我想要做的,我有一个目录中的文件列表。我想逐个读取这些文件,然后提交一个特定的行。 这是我到目前为止所得到的;

patches=/{location}/*.patch
for patch in $patches
do
  echo "Processing $patch file..."
  git apply $patch
  git add --all
  git commit -m | egrep -o "(^Subject: \[PATCH [0-9]\/[0-9]\].)(.*)$" $f
  echo "Committed $patch file..."
done

无法让egrep正则表达式传递正确的提交消息。 以下是补丁文件中的示例行;

.....
Subject: [PATCH 1/3] XSR-2756 Including ldap credentials in property file.  
......

我只想捕获“XSR-2756在属性文件中包含ldap凭证。”并将其用作git的提交描述。

3 个答案:

答案 0 :(得分:3)

假设你有GNU grep,请使用Perl look-behind:

git commit -m "$(grep -Po '(?<=Subject: \[PATCH \d/\d\].).*') $patch"

答案 1 :(得分:1)

在这种情况下不要使用-o egrep(因为你匹配了一堆你不想打印的东西)。相反,只需匹配整行并将其管道化为“cut”(或sed,或其他会修剪一行前缀的东西。)

另外,你将git commit的输出传递给egrep,不提供egrep的输出作为git commit的命令行选项...我想你想要的东西:

git commit -m "$(egrep '<your regexp here>' $f | cut -d] -f2-)"

答案 2 :(得分:1)

我将sed用于此

git commit -m | sed -r -n 's#^Subject: \[PATCH [0-9]/[0-9]\] ##p;'