【问题标题】:Is there a Miller function to recognize csv numbers formatted as currency as numbers rather than string?是否有米勒函数可以将格式化为货币的 csv 数字识别为数字而不是字符串?
【发布时间】:2020-12-30 07:58:15
【问题描述】:

我最近发现了用于批处理 csv 文件的 Miller (mlr) 并喜欢它,但似乎原始数据中格式化为货币的数字被 Miller 识别为字符串,因此尝试对它们执行数学函数会返回一个错误。

这是一个虚拟示例:

mlr --csv --opprint put '$total=$amt+$tax1+$tax2' data.csv

返回:

name     amt    tax1  tax2  total
producta $50.00 $2.50 $4.50 (error)
productb $60.00 $3.00 $5.40 (error)
productc $70.00 $3.50 $6.30 (error)
productd $80.00 $4.00 $7.20 (error)
producte $90.00 $4.50 $8.10 (error)

我发现的最佳解决方法是在每个单独的列上使用 ssub 来删除美元符号,然后我可以将数据相加。

例子:

mlr --csv --opprint put '$amt=ssub($amt,"$","");$tax1=ssub($tax1,"$","");$tax2=ssub($tax2,"$","")' then put '$total=fmtnum($amt+$tax1+$tax2,"%3.2f")' data.csv

返回:

name     amt   tax1 tax2 total
producta 50.00 2.50 4.50 57.00
productb 60.00 3.00 5.40 68.40
productc 70.00 3.50 6.30 79.80
productd 80.00 4.00 7.20 91.20
producte 90.00 4.50 8.10 102.60

虽然这种解决方法很有效,但效率不高。在具有很多列的 csv 文件中,这种方法需要大量的清理并且容易出错。有没有更好的方法让 Miller 将货币格式的数字识别为数字而不是文本?

【问题讨论】:

    标签: miller


    【解决方案1】:

    这是不可能的。

    您可以使用全局搜索和替换

    mlr --csv put -S '                                                                                              1 ↵
      for (k in $*) {
        $[k] = gsub($[k], "[$]", "");
      }
    ' then merge-fields -k -a sum -r '(amt|tax)' -o out input.csv
    

    拥有

    +----------+-------+------+------+------------+
    | name     | amt   | tax1 | tax2 | out_sum    |
    +----------+-------+------+------+------------+
    | producta | 50.00 | 2.50 | 4.50 | 57.000000  |
    | productb | 60.00 | 3.00 | 5.40 | 68.400000  |
    | productc | 70.00 | 3.50 | 6.30 | 79.800000  |
    | productd | 80.00 | 4.00 | 7.20 | 91.200000  |
    | producte | 90.00 | 4.50 | 8.10 | 102.600000 |
    +----------+-------+------+------+------------+
    

    而且这样有很多列也不成问题

    【讨论】:

      猜你喜欢
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2010-10-28
      相关资源
      最近更新 更多