ruchi
ruchi

Reputation: 21

awk printf a particular column in a file

I want to print a particular column (in this case column 7) of my file in scientific notation, whereas rest of the columns get printed as is.

How can I selectively use printf only for column 7 and just print for first 6 columns?

example input:

C   6   12.011  0.51    3.56E-01    4.60E-01    0.458399
CA  6   12.011  -0.15   3.55E-01    2.93E-01    0.291708
CAI 6   12.011  -0.25   3.55E-01    3.05E-01    0.30421
CC  6   12.011  0.62    3.56E-01    2.93E-01    0.291708

desired output:

C   6   12.011  0.51    3.56E-01    4.60E-01    4.58E-01
CA  6   12.011  -0.15   3.55E-01    2.93E-01    2.92E-01
CAI 6   12.011  -0.25   3.55E-01    3.05E-01    3.04E-01
CC  6   12.011  0.62    3.56E-01    2.93E-01    2.92E-01

Upvotes: 0

Views: 779

Answers (2)

Sundeep
Sundeep

Reputation: 23667

To change only the last column without affecting spacing of other fields:

$ cat ip.txt 
C   6   12.011  0.51    3.56E-01    4.60E-01    0.458399
CA  6   12.011  -0.15   3.55E-01    2.93E-01    0.291708
CAI 6   12.011  -0.25   3.55E-01    3.05E-01    0.30421
CC  6   12.011  0.62    3.56E-01    2.93E-01    0.291708

$ perl -pe 's/\S+$/sprintf "%.2E", $&/e' ip.txt 
C   6   12.011  0.51    3.56E-01    4.60E-01    4.58E-01
CA  6   12.011  -0.15   3.55E-01    2.93E-01    2.92E-01
CAI 6   12.011  -0.25   3.55E-01    3.05E-01    3.04E-01
CC  6   12.011  0.62    3.56E-01    2.93E-01    2.92E-01

If some other column is required:

$ perl -pe 's/^(\S+\s+){2}\K\S+/sprintf "%.2E", $&/e' ip.txt 
C   6   1.20E+01  0.51    3.56E-01    4.60E-01    0.458399
CA  6   1.20E+01  -0.15   3.55E-01    2.93E-01    0.291708
CAI 6   1.20E+01  -0.25   3.55E-01    3.05E-01    0.30421
CC  6   1.20E+01  0.62    3.56E-01    2.93E-01    0.291708

Upvotes: 0

jas
jas

Reputation: 10865

You can use sprintf:

$ awk -v OFS="\t" '{ $7 = sprintf("%.2E", $7) }1' input.txt
C   6   12.011  0.51    3.56E-01    4.60E-01    4.58E-01
CA  6   12.011  -0.15   3.55E-01    2.93E-01    2.92E-01
CAI 6   12.011  -0.25   3.55E-01    3.05E-01    3.04E-01
CC  6   12.011  0.62    3.56E-01    2.93E-01    2.92E-01

Upvotes: 2

Related Questions