views:

205

answers:

4

You can do 'ls -l' to get a detailed directory listing like this:

-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt
A: 

Here's a perl script that will filter the output of 'ls -l' to add the commas. If you call the script commafy.pl then you can alias 'ls' to 'ls -l | commafy.pl'.

#!/usr/bin/perl -p
# pipe the output of ls -l through this to add commas to numbers.

s/(.{5} )(\d{4,}) /truncatePre($1,$2).commafy($2).' '/e;


# adds commas to an integer as appropriate  
sub commafy
{
  my($num) = @_;
  my $len = length($num);
  if ($len <= 3) { return $num; }
  return commafy(substr($num, 0, $len - 3)) . ',' . substr($num, -3);
}

# removes as many chars from the end of str as there are commas to be added
#   to num
sub truncatePre
{
  my($str, $num) = @_;

  $numCommas = int((length($num)-1) / 3);

  return substr($str, 0, length($str) - $numCommas);
}
dreeves
+8  A: 

If the order of magnitude is all you're interested in, ls -lh does something like this:

-rw-r----- 1 alice themonkeys 626M 2007-02-05 01:15 foo.log
-rw-rw-r-- 1 bob   bob        699M 2007-03-12 23:14 bar.txt
JB
Nice! Thanks! I didn't know about the -h switch. For most everyday use, that's probably better than adding commas.
dreeves
+3  A: 

I don't think 'ls' has exactly that capability. If you are looking for readability, 'ls -lh' will give you file sizes that are easier for humans to parse.

-rw-rw-rw-  1 alice themonkeys 1.2G 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob        244M 2008-08-20 05:30 bar.txt
postfuturist
+1  A: 

Actually, I was looking for a test for a young trainee and this seemed ideal. Here's what he came up with:

for i in $(ls -1)
do
    sz=$(expr $(ls -ld $i | awk '{print $5}' | wc -c) - 1)
    printf "%10d %s\n" $sz $i
done

It gives the order of magnitude for the size in a horribly inefficient way. I'll make this community wiki since we're both interested how you rate his code, but I don't want my rep suffering.

Feel free to leave comments (be gentle, he's a newbie, though you wouldn't guess it by his shell scripting :-).

paxdiablo