태그 중 하나에서 패턴 일치 후 sed를 사용하여 xml에서 추출하려면 어떻게 해야 합니까?

태그 중 하나에서 패턴 일치 후 sed를 사용하여 xml에서 추출하려면 어떻게 해야 합니까?
<Response 
            <MessageID>ID:c3e2</MessageID>
             <Year>2018</Year>
            <ClntID>ABC</ClntID>
            <ParticipantID>12346789</ParticipantID>
            <ProductType>RU</ProductType>
           <Date>19010101<tDate>
          </Response>

위 응답에서 참가자 ID 값이 12346789인 경우에만 전체 응답을 복사하고 싶습니다. sed 또는 grep 명령을 사용하여 이를 어떻게 달성할 수 있습니까?

답변1

특별히 요청하셨으니 sed그렇게 하세요.

$ 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>
$

비슷한 코드sed - 행이 조건과 일치하면 패턴 범위와 일치하는 행을 인쇄합니다.@John1024를 통해

답변2

XML이 올바른 형식이고 오류가 없으며(질문의 XML에 오류가 있음) 이것이 Response문서의 루트 노드라고 가정하고 다음을 사용하십시오.XML 스타:

$ 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>

/Response/ParticipantID노드 값이 이면 문서 사본이 반환됩니다 12346789.

XPATH 쿼리는 노드를 /Response[ParticipantID="12346789"]선택 하지만 지정된 값이 있는 경우에만 해당됩니다. 플래그에는 복사가 필요합니다 ( 값을 반환하는 대신 ).ResponseParticipantID-cxmlstarlet-v

관련 정보