0

This question already has an answer here:

Can anyone please explain how does the below sed command works to print a paragraph?

Command:

sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;' file

If possible can anyone explain by breaking this command into pieces so that i can full understand how to modify the command as per different condition.

marked as duplicate by don_crissti, roaima, G-Man, user34720, Timothy Martin May 10 '18 at 17:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

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//'
  • does this mean that it will not print anything after string AAA, within the same paragraph??? – acroniks May 11 '18 at 5:16
  • @UtkarshMishra It will always print the full paragraph regardless of where AAA occurs. – Kusalananda May 11 '18 at 5:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.