user1879573
user1879573

Reputation: 251

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

Upvotes: 0

Views: 138

Answers (3)

user000001
user000001

Reputation: 33327

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

Upvotes: 3

Phylogenesis
Phylogenesis

Reputation: 7880

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.

Upvotes: 2

Kent
Kent

Reputation: 195059

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

Upvotes: 2

Related Questions