awk printf a particular column in a file

核能气质少年 提交于 2021-02-11 12:12:05

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/39577287/awk-printf-a-particular-column-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!