title: Sed substitution on capture group
body: <p>I would like to create a bash function which behaves in the following way:</p>
  
  <ul>
  <li>If passed a string with no flags, add the second argument as flags</li>
  <li>If passed any flag which is in the second argument, keep it in the flags.</li>
  <li>If passed any flag with the letter <code>c</code> or <code>d</code>, we remove it.</li>
  <li>If there is any other character in the flag, we want to keep those and append the second argument as flags.</li>
  </ul>
  
  <p>For example:</p>
  
  <pre class="lang-sh prettyprint-override"><code>my_func 'cmd pattern' 'ab' #=&gt; cmd -ab pattern
  my_func 'cmd -a pattern' 'ab' #=&gt; cmd -ab pattern
  my_func 'cmd -ac pattern' 'ab' #=&gt; cmd -ab pattern
  my_func 'cmd -aef pattern' 'ab' #=&gt; cmd -efab pattern
  my_func 'cmd -deaf pattern' 'ab' #=&gt; cmd -efab pattern
  </code></pre>
  
  <p>This is what I have tried:</p>
  
  <pre class="lang-sh prettyprint-override"><code>function my_func() {
    echo $1 |
    # case with no flags
    sed "/^cmd [^-]/s/^cmd \(.*$\)/cmd -$2 \1/" |
    # case with flags in $2 or `a` or `b`
    sed "/^cmd -[$2ab]+ /s/^cmd -[$2ab] \(.*$\)/cmd -$2 \1/" |
    # case with other flags
    sed ...
  }
  </code></pre>
  
  <p>I'm struggling with the last one. I'm not sure if it's possible, but would love to know if it is.</p>
  
  <p>It would somehow capture the flags (<code>cmd -\([a-z]\)</code>),</p>
  
  <p>then remove <code>abcd</code> from the capture group (<code>sed 's/[abcd]//g'</code> on the group)</p>
  
  <p>then take that value and append <code>ab</code> in the output.</p>
  
  <p>It would also be cool to know if there is a nicer implementation using something other than <code>sed</code></p>