简体   繁体   English

Unix Shell脚本中的算术

[英]Arithmetic in Unix shell Script

I would like to calculate the average of columns 2 and 3 on each line, add 1 to this value and print the whole line. 我想计算每行第2列和第3列的平均值,将此值加1并打印整行。 Some of the average values will be floating point numbers. 一些平均值将是浮点数。

The input file looks like this: 输入文件如下所示:

chr20 2330559 2330737
chr20 2332853 2333041
chr20 2537555 2537711

The output file: 输出文件:

chr20 2330648 2330649
chr20 2332947 2332948
chr20 2537633 2537634

I've tried various combinations of awk without success. 我尝试了各种awk组合,但均未成功。 Any suggestions would be great! 任何建议都很好! Thanks Harriet 谢谢哈丽雅特

Use awk for this: 为此使用awk:

awk '{$2=($2+$3)/2; $3=$2+1}1' file

You can also use the int() function to ensure that the result is an integer: 您还可以使用int()函数来确保结果为整数:

awk '{$2=int(($2+$3)/2); $3=$2+1}1' file

try this one-liner: 试试这个单线:

awk '{a=($2+$3)/2;$2=a;$3=a+1}7' file

it gives 它给

chr20 2330648 2330649
chr20 2332947 2332948
chr20 2537633 2537634

Something like: 就像是:

awk '{ printf("%s %d %d", $1, ($2 + $3) / 2, ($2 + $3) / 2 + 1) }'

You didn't give any indication over what should happen when the average is not an integer. 当平均值不是整数时,您没有给出任何指示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM