How to loop my awk script across different columns?

input

name    a1    a2    a3
g1    0.8    0.4    0.2
g2    -0.2    -0.6    -0.7
g3    0.1    0.6    0.8
g4    0.1    0    0
g5    -0.2    -0.2    -0.2
g6    -0.1    -0.9    -0.9
g7    0    0    0.2

output

a1:2
a2:0
a3:0

I use the following

 awk '{if ($2>=0.5) print $1"\t""1"; else if($2<=-0.5) print $1"\t""-1"}'  input |awk '{ sum+=$2} END {print sum}'
2
awk '{if ($3>=0.5) print $1"\t""1"; else if($3<=-0.5) print $1"\t""-1"}'  input |awk '{ sum+=$2} END {print sum}'
0
awk '{if ($4>=0.5) print $1"\t""1"; else if($4<=-0.5) print $1"\t""-1"}'  input |awk '{ sum+=$2} END {print sum}'
0

But I have many columns. Is there anyway I can apply the same command looping over all the columns that gives the above output at once? thanx in advance.

Try something like:

awk '
  NR==1{
    n=split($0,Header)
    next
  }
  {
    for(i=2; i<=NF; i++) {
      if($i>0.5)  Total++
      if($i<-0.5) Total--
    }
  }
  END{
    for(i=2; i<=n; i++)
      print Header ":" Total
  }
' file

Output:

a1:1
a2:-1
a3:-1
1 Like

You have given incorrect output...
you code is comparing for header column and providing the output as 2, 0, 0.
If you go throug that manually, you will get 1, -1, -1 as output.
Below is the code for that

awk 'NR == 1 {split($0, c, FS); next}
  {if($2 >= 0.5) {v[2] += 1} else if($2 <= -0.5) {v[2] -= 1};
  if($3 >= 0.5) {v[3] += 1} else if($3 <= -0.5) {v[3] -= 1};
  if($4 >= 0.5) {v[4] += 1} else if($4 <= -0.5) {v[4] -= 1}}
  END {for(i = 2; i <= length(c); i++) print c ":" v}' file

yes. you are right. thanx for pointing it out.