PROBLEM: ls --color outputs undesirable leader and trailer

gregory mott <[email protected]> 29 Apr 2003 10:44:25 +0100
Newsgroups gmane.comp.gnu.fileutils.bugs
Message-ID <1051609465.4534.629.camel@ruby>
ls --version:    ls (fileutils) 4.1       (redhat7.3+up2date)
sort --version:  sort (textutils) 2.0.21  (redhat7.3+up2date)

problem:  ls --color's output is almost compatible with sort, but is
wanting of a minor modification.

in the output from ls --color, every filename is preceeded and followed
by escape sequences to set color.  so far so good.

but also, ls --color surrounds the entire output with completely
unnecessary leading and trailing escape sequences.  it is these that
cause strange and undesirable sort behaviour.  when these are removed,
sort is happy.

example:
ls --color > /tmp/foo
sort -fs -k1.1,1.1 < /tmp/foo
vim /tmp/foo
^[[00msrwx------    1 g        root            0 Tue Apr 29 04:13:06 2003 ^[[01;35mgpmctl^[[00m=
prw-------    1 root     root            0 Tue Apr 29 04:12:49 2003 ^[[40;33minitctl^[[00m|
brw-rw----    1 root     disk       1, 250 Thu Apr 11 15:25:14 2002 ^[[40;33;01minitrd^[[00m
srw-rw-rw-    1 root     root            0 Tue Apr 29 04:12:46 2003 ^[[01;35mlog^[[00m=
crw-------    1 root     root      10,   0 Thu Apr 11 15:25:14 2002 ^[[40;33;01mlogibm^[[00m
drwxr-xr-x    4 root     root         4096 Wed Sep 18 18:27:54 2002 ^[[01;34mlogicalco^[[00m/
crw-------    1 root     root      10,   0 Thu Apr 11 15:25:14 2002 ^[[40;33;01mlogimouse^[[00m
^[[m

workaround hack (remove escape sequences if at bol):
alias listsort="awk $'/^\^[/{\$0=substr(\$0,6)}\n
                    length>0{print}'|sort -fs -k1.1,1.1"        #listsort separates directories from files
ls --color|listsort