title: Bash sort command not sorting colored output correctly
body: <p>When using <code>/bin/sort</code> in bash I find that output is often inappropriately sorted when it comes from colorized input.</p>
  
  <p>For example in a directory with the following contents:</p>
  
  <pre><code>$ ls
  dir1          (directory, printed in blue)
  dir2          (directory, printed in blue)
  dir3          (directory, printed in blue)
  afile         (file, printed in white)
  file1         (file, printed in white)
  file2         (file, printed in white)
  file3         (file, printed in white)
  </code></pre>
  
  <p>I would expect <code>ls | sort</code> to sort <code>afile</code> first, then <code>dir1</code>, etc.  Instead I get:</p>
  
  <pre><code>$ ls | sort
  dir2
  dir3
  dir1
  afile
  file1
  file2
  file3
  </code></pre>
  
  <p>I have tried quite a few options on <code>sort</code> (-d, -g, -h, -n) to no avail.</p>
  
  <p>The only way I have been able to fix the issue is by explicitly turning the color output of <code>ls</code> off:</p>
  
  <pre><code>$ ls --color=never | sort
  afile
  dir1
  dir2
  dir3
  file1
  file2
  file3
  </code></pre>
  
  <p>But this feels like a work-around, not a solution to the problem.  I keep thinking there must be a way to keep the color in the final output, if only for cases where turning off the color is not an option (e.g. for commands other than <code>ls</code> that may not easily support disabling color).</p>
  
  <p>How would one force sort to act only on the printed characters (i.e. just the file and directory names)?  I would be interested to see how to cleanly remove the color output after the fact (I've tried <code>strings</code> for this but get the color specifiers <code>[01;34m</code> for the blue text) and especially interested in whether one can preserve the color output after sorting.</p>