awk to add one to column based on condition

Viewed 90

Trying to add a awk condition that will add one to $2 if the sum of $3 - $2is greater than one, The below has a syntax error on the if line. Thank you :).

file

2   21002880    21002881
17  3476163 3476186
11  108292759   108292760
2   218661210   218661265
2   21002865    21002866

desired

2   21002880    21002881
17  3476164 3476186
11  108292759   108292760
2   218661211   218661265
2   21002865    21002866

awk

awk 'BEGIN {FS=OFS="\t"} {sum+=$3-$2}  # define FS, OFS, and sum
  if((sum > 1)) {  # condition check
     print $1,$2+1,$3  # print desired output
     next     # goto next line
  }
 }1' file.txt
2 Answers

Another short one:

awk -v OFS="\t" '{$2+=($3-$2>1)}1' file

Output:

2       21002880        21002881
17      3476164 3476186
11      108292759       108292760
2       218661211       218661265
2       21002865        21002866

I missed a { and needed sum=$3-$2

awk 'BEGIN {FS=OFS="\t"} {sum=$3-$2}  # define FS, OFS, and sum
 {
  if((sum > 1)) {  # condition check
    print $1,$2+1,$3  # print desired output
    next     # goto next line
 }
}1' file.txt
Related