使用awk匹配一行中的字符串,并匹配第一个匹配的第N行

时间:2018-06-16 18:34:59

标签: bash git shell awk

/tmp/foo具有git show命令的输出,我只需要找出超级项目的更改,所以我试图找到+++和3&rd行的行从那里匹配+Subproject commit,并打印匹配,从给定的/ tmp / foo示例,我喜欢打印:

dir1 bcb1fe0dda395c82ac1fc8ec71fe87663e665147
dir2 3e56b818c92f7a0f7872abe37d30718a93ecda74

文件内容/ tmp / foo:

$ cat /tmp/foo
commit 8a47e9c8f210eca65e902c488cd356d4c00e992e
Author: name <email@google.com>
Date:   Thu Jun 14 16:30:05 2018 -0900

    Test

    Change-Id: Idb62494991d22fa59e66c22367a3770b95bb16

diff --git a/file.txt b/file.txt
index 610e336..c362aba 100644
--- a/file.txt
+++ b/file.txt
@@ -16,7 +16,8 @@
 #
 # A test
 #
-#  #..
+#  #....
+# This is a test
 #
 #
 #
diff --git a/dir1 b/dir1
index 1f98e97..ade1fe9 160000
--- a/dir1
+++ b/dir1
@@ -1 +1 @@
-Subproject commit 1e25e071aef54240f5899a312dd3bee29150e607
+Subproject commit bcb1fe0dda395c82ac1fc8ec71fe87663e665147
diff --git a/dir2 b/dir2
index f54d099..3e99b81 160000
--- a/dir2
+++ b/dir2
@@ -1 +1 @@
-Subproject commit f66c051f20b0948a5b8947456b516e870b54368e
+Subproject commit 3e56b818c92f7a0f7872abe37d30718a93ecda74
到目前为止,我试过这个,我相信我做得不对。我不一定要使用awk。

$ awk '/\+\+\+/{if(nr[NR+3] ~ /\+Subproject/){nr[NR+3];print nr[NR-3];print nr[NR]};next}; NR in nr'  /tmp/foo
 # A test
+Subproject commit bcb1fe0dda395c82ac1fc8ec71fe87663e665147
+Subproject commit 3e56b818c92f7a0f7872abe37d30718a93ecda74

1 个答案:

答案 0 :(得分:1)

编辑: 在不使用getline的情况下添加解决方案可能会对您有所帮助。

awk '
/^\+\+\+/{
  sub(/.*\//,"",$NF);
  val=$NF;
  flag=1;
  count=""}
flag{
  count++;}
/^+Subproject commit/ && count==4{
  print val,$NF;
  flag=count="";
  next
}'  Input_file

关注awk可能会对您有所帮助。

awk '
/+++/{
  sub(/.*\//,"",$(NF-1));
  getline;
  getline;
  getline;
  if($0 ~ /^+Subproject commit/){
    print "dir"++count,$NF}
}'  Input_file

根据@Cyrus评论添加以下内容。

awk -F '[/ ]' '
/^\+\+\+/{
  dir=$NF;
  getline;
  getline;
  getline;
  if($0 ~ /^+Subproject commit/){
    print dir,$NF}
}'  Input_file