Skip to content
Advertisement

How do I grep/awk multiple lines from a cluster based on a pattern?

is there a way I can grep/awk multiple lines from a cluster based on a pattern?

I have a file as follows:

File.txt

JavaScript

And the pattern is – “Dogs”, I would like the output to be:

JavaScript

Is this possible?

Advertisement

Answer

JavaScript

or

JavaScript

Notes:

  • The first version loads the entire file into memory (but not the second).
  • Both versions search the first line of the record as well as the subsequent lines.
  • You can place the second program all on one line if you want.
  • These address two bugs in karakfa’s answer:
    • These don’t add a leading blank line if the first record doesn’t match.
    • These don’t remove the final line feed if the last record doesn’t match.
  • Related: Specifying file to process to Perl one-liner.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement