Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

awk - Divide all columns by one, line by line, printing NA where division by 0

I have a tab delim file

1A      865     508     512    0       2       0       0
1B      0       0       0      0       0       0       1      

I need to divide every col from $3 on by $2 and multiply the resulting by 100 line by line, printing NA where division by 0.

So that I have

1A  865 58.73  59.19 0.00  0.23  0.00  0.00  0.00  0.00
1B  0   NA     NA    NA    NA    NA    NA    NA    NA

I tried

awk 'BEGIN{FS=OFS=""} FNR>1 {for(i=3;i<=NR;i++) $i={print $0""($2?$i/$2*100:"NaN")1}'

but I get "unexpected newline or end of string"

question from:https://stackoverflow.com/questions/65866132/divide-all-columns-by-one-line-by-line-printing-na-where-division-by-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Could you please try following based on your shown samples only. Basically you need to make 2 major changes here, 1st your loop should run till value of NF NOT NR, 2nd- you are using print while assigning current field's value which we don't want to do. I have written this on mobile so haven't tested it yet but should work I believe.

awk '
BEGIN{
  FS=OFS=""
}
FNR>1{
  for(i=3;i<=NF;i++){
    $i=($2?($i/$2)*100:"NaN")
  }
}
1' Input_file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...