How to grep for text in a file and display the paragraph that has the text

awkgrepperlsedtext processing

Below is the text in the file:

Pseudo name=Apple
Code=42B
state=fault

Pseudo name=Prance
Code=43B
state=good

I need to grep for "42B" and get the output from the above text like:

Pseudo name=Apple
Code=42B
state=fault

Does anyone have idea on how to achieve this using grep/awk/sed?

Best Answer

With awk

awk -v RS='' '/42B/' file

RS= changes the input record separator from a newline to blank lines. If any field in an record contains /42B/ print the record.

'' (the null string) is a magic value used to represent blank lines according to POSIX:

If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is.

The output paragraphs will not be separated since the output separator remains a single newline. To ensure that there is a blank line between output paragraphs, set the output record separator to two newlines:

awk -v RS='' -v ORS='\n\n' '/42B/' file
Related Question