awk subtract each row of a column from 1 where row greater than .5

Viewed 92

I have:

col
.4
.3
.7

I want:

col
.4
.3
.3

My column is one column amongst others, I only want to apply this math to this column only while leaving all others unchanged. I want to print all columns (after applying the math).

I tried this:

awk '{print $0, ($1 > .5 ? 1 - $1 : $1)}' 

but does not seem to work.

2 Answers

print $0, ($1 > .5 ? 1 - $1 : $1) adds an extra column, it does not change the existing ones. Try:

$ awk 'NR>1 && $1>.5 {$1 = 1-$1} {print}' file
col
.4
.3
0.3

If you don't like the leading zeros (0.3) try:

$ awk 'NR>1 && $1>.5 {$1=1-$1;sub(/0*/,"",$1)} {print}' file
col
.4
.3
.3

Another way of thinking:

awk '$1~/\.[6-9]/ {$1=1-$1;sub("^0","",$1)} 1' file
col
.4
.3
.3

if it's only one digit after point, then it should work, otherwise use normal way.

Related