简体   繁体   中英

Use awk to print $0 using the same format for all columns

Taking an example, I have a file with one line

0.1 35 23.0e3 4.0D+03

and I'd like to convert it to a nicely formatted file like

1.00e-01 3.50e+01 2.30e+04 4.00e+03

I know we can do this in awk using the printf statement, but that would be tedious if the number of columns is big. I was wondering if there is a way to set the format for all columns, and just use print $0 ?

Considering this input:

$ a=$'0.1 35 23e3\n0.2 36 24e3';echo "$a"
0.1 35 23e3
0.2 36 24e3

This gnu awk will achieve what you expect without looping over the fields:

$ echo "$a" |awk '{printf "%.2e%s",$0,RT}' RS="[ ]|\n"
1.00e-01 3.50e+01 2.30e+04
2.00e-01 3.60e+01 2.40e+04

I have intentionally exclude 4.0D+03 since does not seem valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM