【问题标题】:Convert floating point numbers to user defined output using AWK使用 AWK 将浮点数转换为用户定义的输出
【发布时间】:2021-02-22 01:22:07
【问题描述】:

我正在尝试使用 awk, e-01 -> $\exp 10^{-01}$ 将浮点数(列)从文本文件转换为用户定义的输出p>

测试输入:

1.2e-01  
1.8e-02  
1.12e-03  
1.222e+04 
1.23e+05  
441.2e+05 
221.2e+06  

期待结果

1.2$\exp 10^{-01}$
1.8$\exp 10^{-02}$
1.12$\exp 10^{-03}$
1.222$\exp 10^{+04}$
1.23$\exp 10^{+05}$
441.2$\exp 10^{+05}$
221.2$\exp 10^{+06}$

我使用了下面的命令“awk '{printf "%.4e\n", $1}'”,并没有解决这个问题。

任何帮助将不胜感激。

【问题讨论】:

    标签: linux shell awk sed grep


    【解决方案1】:

    您能否尝试仅在 GNU awk 中使用所示示例进行跟踪、编写和测试。

    awk '{sub(/ +$/,"");sub(/e/,"$\\exp ");sub(/[-+]/,"10^{&");$0=$0"}$"} 1' Input_file
    

    说明:为上述添加详细说明。

    awk '                   ##Starting awk program from here.
    {
      sub(/ +$/,"")         ##Substituting space at last of line with NULL in each line.
      sub(/e/,"$\\exp ")    ##Substituting e with $\\exp in current line.
      sub(/[-+]/,"10^{&")   ##Substituting either - or + with 10^{ with matched - or +
      $0=$0"}$"             ##Appending }$ at current line.
    }
    1                       ##1 will print current line.
    ' Input_file            ##Mentioning Input_file name here.
    

    【讨论】:

      【解决方案2】:

      您可以将这个简单的sed 替换与捕获组和反向引用一起使用:

      sed -E 's/e([+-][0-9]+)/$\\exp 10^{\1}$/' file
      
      1.2$\exp 10^{-01}$
      1.8$\exp 10^{-02}$
      1.12$\exp 10^{-03}$
      1.222$\exp 10^{+04}$
      1.23$\exp 10^{+05}$
      441.2$\exp 10^{+05}$
      221.2$\exp 10^{+06}$
      

      【讨论】:

        【解决方案3】:

        我会将输入视为文本并进行两次后续替换,即:

        awk '{$0=gensub("e", "$\\\\exp 10^", 1); $0=gensub("(-|+)([0-9]+)[[:blank:]]+", "{\\1\\2}$", 1); print}' file.txt
        

        file.txt 为:

        1.2e-01  
        1.8e-02  
        1.12e-03  
        1.222e+04 
        1.23e+05  
        441.2e+05 
        221.2e+06 
        

        那么输出是:

        1.2$\exp 10^{-01}$
        1.8$\exp 10^{-02}$
        1.12$\exp 10^{-03}$
        1.222$\exp 10^{+04}$
        1.23$\exp 10^{+05}$
        441.2$\exp 10^{+05}$
        221.2$\exp 10^{+06}$
        

        解释:我改变整行($0),首先我用$\exp 10^替换e\需要转义),其次我搜索符号(-+) by(一位或多位数字)后跟一个或多个空格或制表符,我将其替换为{signdigits}$。最后我print改行了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-29
          • 1970-01-01
          • 2016-09-02
          • 2012-10-07
          • 2023-03-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多