Home > Software design >  How to convert file size to human readable and print with other columns?
How to convert file size to human readable and print with other columns?

Time:06-18

Hi I want to convert this command output 5th column to human readable format. For ex if this is my input :

-rw-rw-r-- 1 bhagyaraj bhagyaraj  280000   Jun 17 18:34 demo1
-rw-rw-r-- 1 bhagyaraj bhagyaraj  2800000  Jun 17 18:34 demo2
-rw-rw-r-- 1 bhagyaraj bhagyaraj  28000000 Jun 17 18:35 demo3

To something like this :

-rw-rw-r--  280K demo1
-rw-rw-r--  2.8M demo2
-rw-rw-r--  28M  demo3

I tried this command, but this will return only the file size column.

ls -l | tail -n  2 |awk '{print $5 | "numfmt --to=si"}'

ls is just for example my use case is very huge and repeated execution must be avoided

Any help would be appreciated :)

CodePudding user response:

Just use -h --si

  -h, --human-readable       with -l and -s, print sizes like 1K 234M 2G etc.
      --si                   likewise, but use powers of 1000 not 1024

So the command would be

ls -lh --si | tail -n  2

CodePudding user response:

Using awk

$ ls -l | awk '{if($5 > 1000000) size=$5/1000000"M"; else if ($5 < 1000) size=$5"B"; else if(length($5) <= 4) size=sprintf("%.1fK", $5/1000);else size=$5/1000"K"}{print  $1,size,$NF}'
-rw-rw-r-- 280K demo1
-rw-rw-r-- 2.8M demo2
-rw-rw-r-- 28M demo3
$ cat script.awk
{
    if ($5 > 1000000) 
        size=$5/1000000"M"
    else 
        if ($5 < 1000) 
            size=$5"B"
    else 
        if (length($5) <= 4) 
            size=sprintf("%.1fK", $5/1000)
        else 
            size=$5/1000"K"
} {
    print  $1,size,$NF
}
$ ls -l | awk -f script.awk
-rw-rw-r-- 280K demo1
-rw-rw-r-- 2.8M demo2
-rw-rw-r-- 28M demo3
  • Related