【问题标题】:How to use awk for pattern matching in group of lines如何在一组行中使用 awk 进行模式匹配
【发布时间】:2019-09-17 20:28:03
【问题描述】:

我正在寻找 awksedgrepbash 中的任何其他选项 来分组行根据模式分成集合,然后根据单词黑名单从集合池中排除集合。

例如,请参见下面的示例,我想打印其中没有“hello”和“idle”的所有集合。未来黑名单可能会比这两个词更多。

我尝试使用 awk 和 grep,但无法提出一个好的解决方案来实现这一点。

$ grep -v "hello" test.out | more
 row1  set 1
 row2
 --
 row1  set 2
 row2
 row3 is "fine"

输入文件test.out

row1  set 1 
row2
row3 is "hello"
--
row1  set 2 
row2
row3 is "fine"
--
row1  set 3 
row2
row3  is "idle"
--
row1  set 4 
row2
row3
...
--
row1  set n
row2
row3

预期输出:

row1  set 2 
row2
row3 is "fine"
--
row1  set 4 
row2
row3
...
--
row1  set n
row2
row3

【问题讨论】:

    标签: regex bash awk sed grep


    【解决方案1】:

    使用gnu awk,您可以将记录选择器设置为--,然后说我们不需要helloidle 的记录

    awk 'BEGIN{RS=ORS="--"};!(/hello/||/idle/)' file
    
     row1  set 2
     row2
     row3 is "fine"
     --
     row1  set 4
     row2
     row3
     ...
     --
     row1  set n
     row2
     row3
    --
    

    这个!(/hello/||/idle/)也可以写成这样!/hello/&&!/idle/或ED写成!/hello|idle/

    也可以像这样使用其他分隔符:

    awk 'BEGIN{RS=ORS="row1  set"};!/hello/&&!/idle/' file
    

    【讨论】:

    • !/hello|idle/。当然不解决部分或正则表达式匹配,但 OP 还没有告诉我们如何处理任何这些。
    【解决方案2】:

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

    sed -E ':a;N;$!{/^--$/M!ba};/hello|idle/d' file
    

    收集行直到遇到以-- 开头的行,然后如果集合包含helloidle,则删除它们,打印其他所有内容。

    另一种选择:

    sed -nE 'h;:a;n;H;/^--$/!{$!ba};x;/hello|idle/!p' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多