【问题标题】:awk oneliner to extract line next to matching string but not line having the matchawk oneliner 提取匹配字符串旁边的行,但不提取匹配的行
【发布时间】:2020-11-23 13:54:12
【问题描述】:

我有一个文件:

$ cat test.csv
hello foo
needed
bar
blah
blah
bar
hello foo
needed
bar
blah
hello foo
needed
hello foo
needed
bar
blah

我需要提取在 'hello' 旁边有 'bar' 和立即行但不是 'hello' 行的行。到目前为止,我能够提取如下但不能忽略“你好”行。我可以尝试使用另一个 awk 进行提取,但想知道是否有可以一次性处理它的 oneliner?

$ awk '/hello|bar/;/hello/{getline;print}' test.csv
hello foo
needed
bar
bar
hello foo
needed
bar
hello foo
needed
hello foo
needed
bar

编辑: 预期输出-

needed
bar
bar
needed
bar
needed
needed
bar

【问题讨论】:

  • 能否请您在您的问题中发布预期输出示例,以便更清楚,然后让我们知道。
  • 道歉。我已经添加了预期的输出。
  • 另请参阅 lines around matching regexp - 这将帮助您使用比 getline 更安全的方法 ...有关文档,请参阅 gnu.org/software/gawk/manualstackoverflow.com/tags/awk/info 还有其他资源
  • @StrangerThinks:没有块的/hello|bar/; 意味着“如果模式匹配则打印该行”。您可以使用空块/hello|bar/{};...,或将匹配限制为bar,因为hello 部分无论如何都会使用您的下一个awk 子句处理。
  • 知道了。原始文件还有其他行也需要包含在内,并且我假设在每个 awk 子命令中,结果集都会被修剪,因此在第一个 cmd 中添加了一个包含过滤器以包含所有必要的结果,然后是 hello 的附加子句。感谢您的澄清

标签: regex shell unix awk


【解决方案1】:

你可以使用这个awk:

awk 'p || /bar/; { p = $0 ~ /hello/ }' file
needed
bar
bar
needed
bar
needed
needed
bar

详情:

  • p = $0 ~ /hello/:将p 设置为10,具体取决于一行是否匹配hello
  • 如果p == 1 或者如果行匹配barp || /bar/ 将打印一行

【讨论】:

  • 谢谢。它工作完美,感谢您的解释。您介意将我重定向到与上述操作类似的更多文档相关的一些资源吗?
  • Stackoverflow awk 标签有很多很棒的答案:stackoverflow.com/questions/tagged/awk
【解决方案2】:

根据 OP 的示例,您能否尝试以下操作。在https://ideone.com/EzCjLM 链接中编写和测试。

awk '
/hello/{
  found_hello=1
  next
}
found_hello || /bar/{
  print
  found_hello=""
}
' Input_file

说明:为上述添加详细说明。

awk '                     ##Starting awk program from here.
/hello/{                  ##Checking condition if line contains hello string then do following.
  found_hello=1           ##Setting variable found_hello here.
  next                    ##next will skip all further statements from here.
}
found_hello || /bar/{     ##Checking condition if found_hello is SET OR bar is found then do following.
  print                   ##Printing current line here.
  found_hello=""          ##Nullifying found_hello here.
}
' Input_file              ##Mentioning Input_file name here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2015-10-19
    相关资源
    最近更新 更多