AWK由恒定受另一个约束乘以在文本文件中的所有数字 [英] Awk to multiply all numbers in a text file by a constant subject to another constraint

查看:89
本文介绍了AWK由恒定受另一个约束乘以在文本文件中的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有像下列内容的文件:

I have files with contents like the following:

0.23423
0.10093
0.44231
0.45630
0.89999

我想通过一个给定的百分比,以增加每一个号码,比方说,20%以上。所以,我想知道如何用1.2乘以每个值。

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.

的约束我需要施加的是,产品小于或等于1,因为这些值是概率。

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

所以,在伪code,我需要更换每个号码 X MAX(1.0,X给定的文本文件* 1.2)

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

这怎么在awk中被acheived?

How can this be acheived in Awk?

推荐答案

试试这个单行:

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

测试你的例子:

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

如果你想保持彩车的precision,你可以使用的printf

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

这篇关于AWK由恒定受另一个约束乘以在文本文件中的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆