示例文件结构如下
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.999999,1.409999,15.9988999
Biscuit,2.999999,2.409999,15.9988999
输出文件预计采用以下格式:
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99
答案1
在具有 GNU Coreutils 的系统上,您可能会考虑使用numfmt
例如
$ numfmt --delimiter=, --header --field=2- --format='%.2f' --round=down < file.csv
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99
如果您想要传统的 IEEE 从零舍入,请省略该--round=down
指令。
答案2
这符合您的要求:
$ sed -E 's/([0-9]+\.[0-9]{2})[0-9]*/\1/g' file.csv
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99
或者,如果您想对数字进行四舍五入而不是仅删除多余的数字,您可以尝试:
$ perl -pe 's/(\d+\.\d+)/sprintf("%0.2f",$1)/ge' file.csv
Product,Base_Price,Promotion_Price,Discount
Shampoo,2.00,1.41,16.00
Biscuit,3.00,2.41,16.00
答案3
awk -F "," 'NR>1{print $1,$2,$3,$4}' y.txt |awk '{print $1,substr($2,1,4),substr($3,1,4),substr($4,1,5)}'|awk 'OFS="," {print $1,$2,$3,$4}1' filename
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99
答案4
使用 Miller ( mlr
) 将数值截断为两位小数:
$ mlr --csv put 'for (k,v in $*) { is_numeric(v) { $[k] = fmtnum(floor(v*100)/100,"%.2f") } }' file
Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99