1

我想拿起以'---------read-------'开头并以'finish'结尾的行。同时,从下面显示的日志文件中删除重复的段落(仅保留相同段落的最后匹配项)

-------------read-----------  

File reading...  
1 failed  
finish.

[some unrelated messages]

-------------read-----------  
File reading...  
2 failed  
finish.

[some unrelated messages]

-------------read-----------  
File reading...  
1 failed   
finish.  
[some unrelated messages]

在日志文件中,段落有固定的开始行和结束行,但没有固定中间行,所以我用
sed -n -e "/-------------read-----------/,/finish./ p" $input_file_name 的是拾取段落,但无法删除重复的(某些段落可能重复)

我试过使用sed -n "0,/----read---/,/finish/ p"or sed -n "/----read------/,/finish/,{p;q;}",但它们不起作用。

他理想的输出是:

-------------read-----------  
File reading...  
2 failed  
finish.  
-------------read-----------  
File reading...  
1 failed   
finish.

我怎样才能做到这一点?如果有人可以提供帮助,我将不胜感激!

4

4 回答 4

1
$ cat tst.awk
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
!NF { next }
/-------------read-----------/ { inBlock=1; block="" }
inBlock { block = block $0 RS }
/finish/ {
    if (NR==FNR) {
        lastSeen[block] = FNR
    }
    else {
        if (FNR==lastSeen[block]) {
            printf "%s", block
        }
    }
    inBlock=0
}

$ awk -f tst.awk file file
-------------read-----------
File reading...
2 failed
finish.
-------------read-----------
File reading...
1 failed
finish.
于 2015-12-01T20:06:46.890 回答
0

使用类似的逻辑

$ awk '/-+read-+/{k=$0; next} 
            k&&NF{sub(/ *$/,""); k=k RS $0}
         /finish/{if(NR==FNR) a[k]++;
                  else if(!--a[k]) print k; 
                  k=""}' log{,}
-------------read-----------
File reading...
2 failed
finish.
-------------read-----------
File reading...
1 failed
finish.

保留最后匹配的记录会增加额外的复杂性。

于 2015-12-01T20:48:32.337 回答
0

我不确定我们应该在哪里寻找我们不想重复的重复(例如,您的示例输入似乎没有文件名),但您可以通过简单的切换来去除不必要的数据:

$ awk '/^-+read-+/ {show=1} show; $1=="finish." {show=0}' inputfile
于 2015-12-01T21:03:36.473 回答
0

这可能对您有用(GNU sed):

sed -r '/-+read/,/finish\./H;$!d;x;:a;s/(\n-+read.*finish\.)(.*\1)/\2/;ta;s/.//' file

这会将过滤后的行存储在保持空间中,然后使用模式匹配和反向引用来删除重复的段落。然而,这是一个脆弱的解决方案,因为它要求重复的段落是精确的副本(与给出的示例不同)。

于 2015-12-02T08:24:10.760 回答