【问题标题】:Two float numbers ara attached together in my output text file两个浮点数 ara 附加在我的输出文本文件中
【发布时间】:2014-01-13 15:58:16
【问题描述】:

在我的输出文件中,对应于两个浮点数的两列连接在一起,形成一列。此处显示了一个示例,是否可以将这两列彼此分开?

在这里,这应该是由空格分隔的 5 列,但缺少第 3 列和第 4 列之间的空格。有没有办法用一些 UNIX 命令(例如 cut、awk、sed 甚至正则表达式)来纠正这个错误?

3.77388 0.608871 -8216.342.42161 1.88655
4.39243 0.625 -8238.241.49211 0.889258
4.38903 0.608871 -7871.71.52994 0.883976
4.286 0.653226 -8287.322.3195 2.13736
4.29313 0.629032 -7954.651.59168 1.02046

修正后的版本应该是这样的:

3.77388 0.608871 -8216.34 2.42161 1.88655
4.39243 0.625 -8238.24 1.49211 0.889258
4.38903 0.608871 -7871.7 1.52994 0.883976
4.286 0.653226 -8287.32 2.3195 2.13736
4.29313 0.629032 -7954.65 1.59168 1.02046

更多信息:第 4 列始终小于 10,因此小数点左侧只有一位。

我试过用awk:

tail -n 5 output.dat | awk '{print $3}'
-8216.342.42161
-8238.241.49211
-7871.71.52994
-8287.322.3195
-7954.651.59168

有什么办法可以将此列分成两列?

【问题讨论】:

  • 并非没有事先了解第 3 列和第 4 列中的数字范围。
  • 第 4 列的范围总是在 0 和 10 之间。所以我知道第 4 列的小数点左边只有一位!
  • 10 包含在这个范围内吗?
  • 不,一点也不!只有一位数字 0 到 9
  • 我认为这里最好的答案是修复生成原始输出的程序...

标签: regex bash sed awk output


【解决方案1】:

一种解决方案:

sed 's/\(\.[0-9]*\)\([0-9]\.\)/\1 \2/'

【讨论】:

    【解决方案2】:

    使用 Perl 单行:

    perl -pe 's/(\d+\.\d+)(\d\.\d+)/$1 $2/' < output.dat > fixed_output.dat
    

    【讨论】:

    • +1。将其限制为第三个单词:perl -lane '$F[2] =~ s/(\.\d+)(\d\.)/$1 $2/; print "@F"'
    【解决方案3】:

    你的输入文件

        $ cat file
        3.77388 0.608871 -8216.342.42161 1.88655
        4.39243 0.625 -8238.241.49211 0.889258
        4.38903 0.608871 -7871.71.52994 0.883976
        4.286 0.653226 -8287.322.3195 2.13736
        4.29313 0.629032 -7954.651.59168 1.02046
    

    Awk 方法

        awk '{
               n = index($3,".")                        # index of dot from field 3              
               x = substr($3,1,n+3) ~/\.$/ ? n+1 : n+2  # Decision for no of char to consider 
              $3 = substr($3,1,x) OFS substr($3,x+1)    # separate out fields
              $0 = $0                                   # Recalculate fields (number of fields NF)
              $1 = $1                                   # recalculate the record, removing excess spacing (the new field separator becomes OFS, default is a single space)
             }1' OFS='\t' file
    

    结果

        3.77388 0.608871    -8216.34    2.42161 1.88655
        4.39243 0.625       -8238.24    1.49211 0.889258
        4.38903 0.608871    -7871.7     1.52994 0.883976
        4.286   0.653226    -8287.32    2.3195  2.13736
        4.29313 0.629032    -7954.65    1.59168 1.02046
    

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      相关资源
      最近更新 更多