-2
<Response 
            <MessageID>ID:c3e2</MessageID>
             <Year>2018</Year>
            <ClntID>ABC</ClntID>
            <ParticipantID>12346789</ParticipantID>
            <ProductType>RU</ProductType>
           <Date>19010101<tDate>
          </Response>

In the above response, i want to copy the full response,only if the value of participantID is 12346789. How can i achieve this with sed or grep command?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Shri
  • 11
  • 2
    @Shri, I've rolled back your question to the one that steve answered. It's best if you can ask a Good Question initially, so that you get Good, applicable answers. Given the large change, it's probably better that you ask a new question with the new requirements and accept one of the existing answers to this question. – Jeff Schaller Aug 03 '18 at 17:15

2 Answers2

2

Since you specifically asked for sed, here goes.

$ sed -n '/^<Response/{:a;N;/<\/Response>/!ba;/<ParticipantID>12346789/p}' inp
<Response
            <MessageID>ID:c3e2</MessageID>
             <Year>2018</Year>
            <ClntID>ABC</ClntID>
            <ParticipantID>12346789</ParticipantID>
            <ProductType>RU</ProductType>
           <Date>19010101<tDate>
          </Response>
$

Similar code to sed - Print lines matched by a pattern range if one line matches a condition from @John1024

steve
  • 21,892
1

Assuming that the XML is well formed and without errors (the XML in the question has errors), and that Response is the root node of the document, using XMLStarlet:

$ xmlstarlet sel -t -c '/Response[ParticipantID="12346789"]' -nl file.xml
<Response>
            <MessageID>ID:c3e2</MessageID>
             <Year>2018</Year>
            <ClntID>ABC</ClntID>
            <ParticipantID>12346789</ParticipantID>
            <ProductType>RU</ProductType>
           <Date>19010101</Date>
          </Response>

This will give you back a copy of the document if the /Response/ParticipantID node has a value of 12346789.

The XPATH query /Response[ParticipantID="12346789"] will select the Response node, but only if its ParticipantID has the specified value. The -c flag to xmlstarlet asks for a copy (as opposed to -v which would return the values).

Kusalananda
  • 333,661
  • i am sorry i forgot to mention this is present inside a txt file and i need to copy the extracted response to another txt file ..is that possible ? – Shri Aug 03 '18 at 16:33
  • @Shri Of course it's possible. Is it possible that you may show how it's embedded in the rest of the document? (edit your question to add more information) – Kusalananda Aug 03 '18 at 16:39
  • i have changed the question..sorry for the confusion.. i am new to this – Shri Aug 03 '18 at 16:54