简体   繁体   English

将grep匹配管道插入sed

[英]Piping grep matches into sed

I have a file that might look like this: 我有一个可能看起来像这样的文件:

EntryName1
1234
1234
1234
EntryName2

EntryName3
1234
1234
1234
[...]

I need to remove all entries that are followed by an empty line. 我需要删除所有条目后跟一个空行。 I can grep the empty line and the repective entryName with grep -E '^$' -B 1 myFile.txt . 我可以使用grep -E '^$' -B 1 myFile.txt空行和相应的grep -E '^$' -B 1 myFile.txt

Now I would like to somehow pipe these as patterns into sed, in order to remove those lines from the file. 现在,我想以某种方式将它们作为模式传递到sed中,以便从文件中删除这些行。 How do I do that? 我怎么做?

Edit: The expected output would look like this (leaving the blank line would also be okay). 编辑:预期的输出将如下所示(留空行也可以)。

EntryName1
1234
1234
1234
EntryName3
1234
1234
1234
[...]

A shorter awk : 一个较短的awk

awk 'p != "" && NF{print p} {p=$0} END{print p}' file

EntryName1
1234
1234
1234
EntryName3
1234
1234
1234
[...]

Use awk. 使用awk。

awk '/^$/ { a = ""; next }
     { printf "%s", a; a = $0 ORS }
     END { printf "%s",a }' file

带有gawk和multichar RS支持:

gawk 'BEGIN{RS="\n[^\n]+\n\n"}1' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM