简体   繁体   English

在 Bash/Shell 中使用带有 awk 的 jq 将多列四舍五入到小数点后 2 位

[英]Rounding up MULTIPLE COLUMNS to 2 decimal places using jq with awk in Bash/Shell

Pls i need help rounding up multiple columns in this.csv output.请帮助我在 this.csv output 中整理多列。 So far, i've been able to pipe my jq output into awk and round up just a single column but don't know how to round up this 6 columns.到目前为止,我已经能够将 pipe 我的 jq output 转换为 awk 并仅将一个 6 列四舍五入,但不知道如何四舍五入。

This is the demo.json payload这是演示。json 有效载荷

{
  "XXXX": "XXX",
  "XXXXX": "XXXXXXX",
  "stack": {
    "123": {
      "overflow": 6014.4703
    },
    "234": {
      "overflow": 6090.3888
    },
    "356": {
      "overflow": 8973.8136
    },
    "244": {
      "overflow": 5034.4258
    },
    "789": {
      "overflow": 5957.6018
    },
    "545": {
      "overflow": 1225.7363
    }
  }
}

Below is the line of code i have so far for a single column roundup下面是我到目前为止用于单列综述的代码行

cat demo.json | jq -r --argjson H "$(date +%H -d "1 hour ago")" '["Hours", "A", "B", "C", "D", "E", "F"], ([.stack."123".overflow/1000, .stack."234".overflow/1000, .stack."356".overflow/1000, .stack."244".overflow/1000, .stack."789".overflow/1000, .stack."545".overflow/1000] | [$H] + .) | @csv' | awk 'BEGIN{ FS=OFS="," }NR>1{ $3=sprintf("%.2f", $3) }1' > demo.csv

What i'm trying to achieve我想要达到的目标

"Hour","A","B","C","D","E","F"
"09","6.01","6.09","8.97","5.03","5.96","1.23"

Update |= the relevant columns / fields as follows: Divide by 10 , then round , and divide again by 100 .更新|=相关列/字段如下:除以10 ,然后round入,再除以100

.stack[].overflow |= (. / 10 | round / 100)
{
  "XXXX": "XXX",
  "XXXXX": "XXXXXXX",
  "stack": {
    "123": {
      "overflow": 6.01
    },
    "234": {
      "overflow": 6.09
    },
    "356": {
      "overflow": 8.97
    },
    "244": {
      "overflow": 5.03
    },
    "789": {
      "overflow": 5.96
    },
    "545": {
      "overflow": 1.23
    }
  }
}

Demo演示

Add more sprintf s in awk separated by semi colons: ... | awk 'BEGIN{ FS=OFS="," }NR>1{ $2=sprintf("%.2f", $2); $3=sprintf("%.2f", $3); $4=sprintf("%.2f", $4);...etc... }1' > demo.csvawk中添加更多的sprintf ,用分号分隔: ... | awk 'BEGIN{ FS=OFS="," }NR>1{ $2=sprintf("%.2f", $2); $3=sprintf("%.2f", $3); $4=sprintf("%.2f", $4);...etc... }1' > demo.csv ... | awk 'BEGIN{ FS=OFS="," }NR>1{ $2=sprintf("%.2f", $2); $3=sprintf("%.2f", $3); $4=sprintf("%.2f", $4);...etc... }1' > demo.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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