【问题标题】:Using awk to match a string in a line and also match Nth line from first match使用 awk 匹配一行中的字符串,并从第一次匹配中匹配第 N 行
【发布时间】:2018-06-16 18:34:59
【问题描述】:

/tmp/foogit show 命令的输出,我只需要找出超级项目的变化,所以我试图找到+++ 的行和从那里匹配+Subproject commit 的第3 行,并且仅打印匹配项,从给定的 /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

【问题讨论】:

    标签: bash git shell awk


    【解决方案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
    

    【讨论】:

    • dir1 和 dir2 只是一个示例,可以是任何字符串。
    • @rodee,好的,您从哪里获取这些字符串?
    • 我提出这个改变:awk -F '[/ ]' '/^\+\+\+/ {dir=$NF; getline; getline; getline; if($0 ~ /^+Subproject commit/){print dir OFS $NF}}' file
    • @RavinderSingh13,仅当第 n 行以 +++ 开头且第 n+3 行以 +Subproject commit 开头时才打印第 n 行和第 n+3 行
    • @EdMorton,确定 Ed 现在完成了,感谢您的告知。
    猜你喜欢
    • 2014-09-16
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    相关资源
    最近更新 更多