synaptik
synaptik

Reputation: 9519

Awk to multiply all numbers in a text file by a constant subject to another constraint

I have files with contents like the following:

0.23423
0.10093
0.44231
0.45630
0.89999

I want to increase every number by a given percentage, say, 20%. So, I want to know how to multiply each value by 1.2.

The "constraint" I need to impose is that the products be less than or equal to 1, because these values are probabilities.

So, in pseudocode, I need to replace each number X in a given text file by max(1.0,X*1.2).

How can this be acheived in Awk?

Upvotes: 2

Views: 6550

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185530

Using the C-like ternary operator in a one-liner :

awk '{res = $1 * 1.2; print (res > 1) ? 1 : res}' file
0.281076
0.121116
0.530772
0.54756
1

Upvotes: 3

Kent
Kent

Reputation: 195199

try this one-liner:

awk '{p=1.2*$0;$0=p>1?1:p}7' file

test with your example:

kent$  cat f
0.23423
0.10093
0.44231
0.45630
0.89999

kent$  awk '{p=1.2*$0;$0=p>1?1:p}7' f
0.281076
0.121116
0.530772
0.54756
1

if you want to keep the precision of the floats, you could use printf:

awk '{p=1.2*$0;$0=p>1?1:p;printf "%.5f\n",$0}' file

with same input, it gives:

kent$  awk '{p=1.2*$0;$0=p>1?1:p;printf "%.5f\n",$0}' f
0.28108
0.12112
0.53077
0.54756
1.00000

Upvotes: 3

Related Questions