Regex awk oneliner提取匹配字符串旁边的行,但不提取具有匹配项的行
我有一个文件:Regex awk oneliner提取匹配字符串旁边的行,但不提取具有匹配项的行,regex,shell,unix,awk,Regex,Shell,Unix,Awk,我有一个文件: $ 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”和“immediate”的行,而不是“hello”行。到目前为止,我能够提取如下内容,但不能忽略“hello”行。我可以试着用另一个awk提取,但是想知道是否有一个一次就可以处理好的一行程序 $ awk
$ 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”和“immediate”的行,而不是“hello”行。到目前为止,我能够提取如下内容,但不能忽略“hello”行。我可以试着用另一个awk提取,但是想知道是否有一个一次就可以处理好的一行程序
$ 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
您可以使用此
awk
:
awk 'p || /bar/; { p = $0 ~ /hello/ }' file
详细信息:
:将p=$0~/hello/
设置为p
设置为1
,具体取决于行是否匹配0
hello
- 如果
或行与p==1
bar
- 您可以使用此
awk
:
awk 'p || /bar/; { p = $0 ~ /hello/ }' file
详细信息:
:将p=$0~/hello/
设置为p
设置为1
,具体取决于行是否匹配0
hello
- 如果
或行与p==1
bar
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.
根据OP公司的样品,请您尝试以下内容。用link编写和测试 说明:添加上述内容的详细说明
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.
请在您的问题中发布预期输出的样本,以便更清楚,然后让我们知道。抱歉。我已经添加了预期的输出。另请参见-这将帮助您使用比
getline
更安全的方法。。。有关文档,请参阅,并提供其他资源,如well@StrangerThinks:这个/hello | bar/代码>不带块意味着“如果模式匹配,则打印行”。您可以使用一个空块,/hello | bar/{}
,或者将匹配限制为条
,因为hello
部分无论如何都会使用下一个awk子句处理。明白了。原始文件还有其他需要包含的行,我假设在每个awk子命令中,结果集都会被删减,所以在第一个cmd中添加了一个包含过滤器,以包含所有必要的结果,后面是hello的附加子句。感谢您的澄清。请在您的问题中发布预期输出的样本,以便它变得更清楚,然后让我们知道。抱歉。我已经添加了预期的输出。另请参见-这将帮助您使用比getline
更安全的方法。。。有关文档,请参阅,并提供其他资源,如well@StrangerThinks:这个/hello | bar/代码>不带块意味着“如果模式匹配,则打印行”。您可以使用一个空块,/hello | bar/{}
,或者将匹配限制为条
,因为hello
部分无论如何都会使用下一个awk子句处理。明白了。原始文件还有其他需要包含的行,我假设在每个awk子命令中,结果集都会被删减,所以在第一个cmd中添加了一个包含过滤器,以包含所有必要的结果,后面是hello的附加子句。谢谢你的澄清。它工作完美,谢谢你的解释。您是否介意将我转到一些与上述操作类似的更多文档相关的资源?Stackoverflow awk标签有很多很好的答案:谢谢。它工作完美,谢谢你的解释。您是否介意将我重定向到与上述操作类似的更多文档相关的一些资源?Stackoverflow awk标签有很多很好的答案: