Shell scripting to divide numbers inside a file

14,430

Solution 1

martin@dogmeat ~ % cat test 
100
50
25
martin@dogmeat ~ % cat test | while read i; do echo "$i/2" | bc; done
50
25
12
martin@dogmeat ~ % cat test | while read i; do echo "scale = 5; $i/2.0" | bc; done
50.00000
25.00000
12.50000

bc doesn't have a rounding function, so if you want to have those numbers properly rounded you will probably have to implement the function yourself.

Solution 2

If you're OK with integer division:

c=3
while read num; do
    echo $(( num / c ))
done < file

otherwise, you can use

awk -v c=3 '{ print $1/c }' file

Solution 3

To get around the intricacies of shell floating point arithmetic, why not use Perl? Here's a one-liner to do it:

C=3 perl -ne 'printf "%.2f\n",$_/$ENV{C}' your_file

The gargantuan answer to this question may also be interesting to you.

Share:
14,430

Related videos on Youtube

Palash SInha
Author by

Palash SInha

Updated on September 18, 2022

Comments

  • Palash SInha
    Palash SInha almost 2 years

    I have a single column and 12 rows. Each row has numerical values. I want to divide each row values by some constant number (say C) using shell (bash) scripting. How to do this ? Thanks in advance..

  • Angel Todorov
    Angel Todorov almost 11 years
    You can use printf to do the rounding for you
  • Jeff Hewitt
    Jeff Hewitt almost 11 years
    I would use done < test to avoid the UUoC.
  • Alessio
    Alessio almost 11 years
    the trouble with caring about UUoC is that in cat is often just a placeholder for any other command or pipeline that produces output.