Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be done using <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">positive lookahead</a> :</p> <pre><code>perl -pe 's/(.)(?=.*?\1)//g' FILE_NAME </code></pre> <p>The regex used is: <code>(.)(?=.*?\1)</code></p> <ul> <li><code>.</code> : to match any char.</li> <li>first <code>()</code> : remember the matched single char.</li> <li><code>(?=...)</code> : +ve lookahead</li> <li><code>.*?</code> : to match anything in between</li> <li><code>\1</code> : the remembered match.</li> <li><code>(.)(?=.*?\1)</code> : match and remember any char <strong><em>only if</em></strong> it appears again later in the string.</li> <li><code>s///</code> : Perl way of doing the substitution.</li> <li><code>g</code>: to do the substitution globally...that is don't stop after first substitution.</li> <li><code>s/(.)(?=.*?\1)//g</code> : this will delete a char from the input string only if that char appears again later in the string.</li> </ul> <p>This will <strong><em>not</em></strong> maintain the order of the char in the input because for every unique char in the input string, we retain its <strong><em>last</em></strong> occurrence and not the <strong><em>first</em></strong>.</p> <p>To keep the relative order intact we can do what <code>KennyTM</code> tells in one of the comments: </p> <ul> <li>reverse the input line</li> <li>do the substitution as before</li> <li>reverse the result before printing</li> </ul> <p>The Perl one line for this is:</p> <pre><code>perl -ne '$_=reverse;s/(.)(?=.*?\1)//g;print scalar reverse;' FILE_NAME </code></pre> <p>Since we are doing <code>print</code> manually after reversal, we don't use the <code>-p</code> flag but use the <code>-n</code> flag.</p> <p>I'm not sure if this is the best one-liner to do this. I welcome others to edit this answer if they have a better alternative.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload