简体   繁体   中英

Reformat float numbers using awk

I want to match all floating point numbers in the input and replace them with floating point numbers in a different format.

Here is something I tried:

echo "123.45E+00 blah 678.90E+00 blah 3.1415926535897932E+0000" \
    | awk '{gsub(/[0-9]+\.[0-9]+\E\+[0-9]+/,sprintf("%E","&")); print $0}'

Unfortunately, the "&" in the sprintf is a string and not a number so the result is:

0.000000E+00 blah 0.000000E+00 blah 0.000000E+00

That's the numeric format I want but the use of "&" is resulting in zero as the value of the parameter, rather than the matched number.

Changing the "%E" format to "%s" works in that the original string is returned.

The output I'm wanting for the above input is:

1.234500E+02 blah 6.789000E+02 blah 3.141593E+00

Try something like this:

echo "123.45E+00 blah 678.90E+00 blah 3.1415926535897932E+0000" |
  awk '{
    for (i=1; i<=NF; i++)
      sub(/[0-9]+\.[0-9]+\E\+[0-9]+/, sprintf("%.6E", $i), $i)
  }1'

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