 <p>Superficially, it looks as though you need:</p> <pre><code>sed -n '/^IA\/\([NM][0-9][0-9]*\) \([01]\)$/ s//\1;\2/p' test.txt </code></pre> <p>The <code>-n</code> means do not print lines by default. The search pattern looks for lines that match (very exactly) <code>IA/</code> followed by N or M and one or more digits, a space, and a digit 0 or 1 and end of line. The letter and digit string is captured with <code>\(...\)</code>, as is the final digit; the replacement follows the example separating the fields with a semicolon rather than a comma as stated in the question; clearly, to output a comma as stated but not shown is trivial. The line is printed (the trailing <code>p</code>) only when it matches.</p> <p>As well as the comma versus semicolon issue, this answer assumes that the required output is accurate and the NTST line should not appear. However, the wording in the question implies that maybe the NTST line should appear as well. If so, you can simplify the regex by allowing any number of non-blank characters after the N or M:</p> <pre><code>sed -n '/^IA\/\([NM][^]*\) \([01]\)$/ s//\1;\2/p' test.txt </code></pre> <p>It is not clear from that question what should happen to lines such as:</p> <pre><code>IA/N 0 IA/N Z 0 </code></pre>