FelixJN
FelixJN

Reputation: 570

`awk` - define number of digits in exponent when using scientific notation

I have input data using scientific notation as in (TAB-separated)

-2.60000000E-001        -2.84200000E-011        1.00000000E+000 2.45060000E-010 0.00000000E+000 -1.98000000E-012

using awk, I'm extracting some column and do a mathematical operation on another. To make sure that the format is as needed, printf is applied:

awk '{ printf "%9.8E\t%9.8E\n", $1,sqrt($4) }' infile.dat

However in my output the number of digits for the exponent changes from 3 to 2:

-3.00000000E-01 1.90446843E-05

How do I define these in the printf statement, so that I get the desired output:

-3.00000000E-001 1.90446843E-005

Upvotes: 1

Views: 462

Answers (1)

Gunstick
Gunstick

Reputation: 1042

printf uses the stdio and this does not provide a way to set the exponent length. So you need to run your own.

awk 'BEGIN{
  v="-3.00000000E-01 " 
  v=gensub("E([+-])([0-9][0-9]) ","E\\10\\2","",v )
  print v
  exit}'

This puts the value into variable v, then applies a substitution to search for the exponent, and if it is on 2 positions, it adds a 0. If it is already on 3 positions, nothing is added.

gensub is only available in gawk

Upvotes: 3

Related Questions