Extracting XML elements which contains a certain string with sed <p>I have a file like below</p> <pre><code> &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/&gt; &lt;AUDIT_RECORD TIMESTAMP="2013-07-29T17:27:53" NAME="Quit" CONNECTION_ID="12" STATUS="0"/&gt; &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/&gt; &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/&gt; </code></pre> <p>Here each record begin with <code>&lt;AUDIT_RECORD</code> and end with <code>"/&gt;</code> and the record might spread across multiple lines.</p> <p>My requirement is to display result like below</p> <pre><code> &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/&gt; &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/&gt; &lt;AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/&gt; </code></pre> <p>for that purpose I have used</p> <pre><code>sed -n "/Query/,/\/&gt;/p" file.txt </code></pre> <p>but it is displaying the entire file including the record with the string "Quit".</p> <p>Can anyone help me regarding this? Also please let me know if it is possible to match exactly string named "Query" ( like <code>grep -w "Query"</code> ).</p>