Operating System - HP-UX
1752458 Members
6153 Online
108788 Solutions
New Discussion юеВ

Numerical Calculation in Unix:

 
SOLVED
Go to solution
Sharvil Desai
Frequent Advisor

Numerical Calculation in Unix:

Hi,
I have a shell-script from which I do the calculation to find the size of a file in Mb.

SIZE=`ls -l x:/xyz/abc.dat|tr -s " "|cut -d " " -f 5`
SIZE=`expr $SIZE / 1024 / 1024`
However, this does not give me the precise size of the file. It chops off the digits after the decimal point. Can someone please tell me how to preserve two digits after the decimal? Thank you.
"help!"
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Numerical Calculation in Unix:

The shell (or expr) only does integer arithmatic so your plan is doomed. You need to use awk, bc, or Perl.

Here is an awk equivalent:

SIZE=$(ls -l /xyz/abc.dat | awk '{ printf("%8.2f\n",($5 + 0) / (1024 * 1024)) }')
echo "Size = ${SIZE}"

Note: The $5 + 0 was intentional; it forces the argument into numerical context -- a standard awk idiom.
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: Numerical Calculation in Unix:


perl -e 'printf "%8.3f MB\n", (-s "x.x") / (1024*1024)'

or with some more stuff like a size filter around it:

perl -e 'while (<*.trc>) { $s= -s; printf "%8.3f %s\n", $s/(1024*1024), $_ if $s > 999999}'

hth,
Hein.
Sharvil Desai
Frequent Advisor

Re: Numerical Calculation in Unix:

I will use the awk version, since I don't have perl. But thank you both for posting your answers!
"help!"