Bash – Different colour for the KiB range in `ls -l`

bashls

Is there any sane way to highlight the 4th, 5th, and 6th columns from the right of the file size in ls -l? My intention is to make it easy to read a file size be it in bytes, KiBs, or MiBs. I do know about the -h flag, but I find that having to interpret the letters at the end is more cumbersome than just looking and seeing the length of the number (magnitude). This is the same reason why race cars use analogue dials instead of digital.

My target shell is Bash. Thanks.

EDIT: I am looking to highlight the thousands, ten thousands, and one hundred thousands places of the size column. Like this: 123456789

Best Answer

Maybe something like:

ls -l | perl -pe 'BEGIN{@color=(0,2,3,1,5,4)}
  s{((?:\S+\s+){4})(\d+)}{"$1\e[3" . 
  $color[log($2||1)/log(2)/10] . "m$2\e[m"}e'

For black (or whatever the default foreground colour is on your terminal) for sizes from 0 to 1023, green from 1k to 1M, yellow for 1M to 1G, then red, purple, blue.

Edit. Based on your edited requirements:

ls -l | perl -pe 's{^((?:\S+\s+){4}\d*)(\d{3})(?=\d{3})}
                   {$1\e[31;1m$2\e[m}'
Related Question