简体   繁体   中英

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. 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. Any suggestions would be great! Thanks Harriet

Use awk for this:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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