【发布时间】: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/manual 和 stackoverflow.com/tags/awk/info 还有其他资源 -
@StrangerThinks:没有块的
/hello|bar/;意味着“如果模式匹配则打印该行”。您可以使用空块/hello|bar/{};...,或将匹配限制为bar,因为hello部分无论如何都会使用您的下一个awk 子句处理。 -
知道了。原始文件还有其他行也需要包含在内,并且我假设在每个 awk 子命令中,结果集都会被修剪,因此在第一个 cmd 中添加了一个包含过滤器以包含所有必要的结果,然后是 hello 的附加子句。感谢您的澄清