The command
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;' file
prints paragraphs that contain the string AAA
.
This invokes sed
with the following sed
script:
/./{
H
$!d
}
x
/AAA/!d
Annotated version:
/./{ # When hitting a line that contains at least one character...
H; # Append the line to the "hold space".
$!d; # If it's not the last line, delete it.
}
x; # Swap the hold space and the pattern space.
/AAA/!d; # Delete the pattern space if it does not contain the string "AAA"
# (implicit print)
So, in short, it collects line after line in the "hold space" (a general purpose buffer in sed
), and when it finds an empty line (the /./
pattern does not match), it determines if the stored collection of lines contain the string AAA
and prints it if it does.
This is also described in an answer here: GREP / SED or AWK: Print entire paragraph in a file on pattern match
Given the file
this is
a paragraph
this is
another one
this paragraph
contains the string
AAA
It would output the last paragraph (with a leading empty line).
To get rid of the empty line that will be preceding each outputted paragraph (if this is what you want), use
/./{
H
$!d
}
x
/AAA/!d
s/\n//
Or, on the command line
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;s/\n//'