
範例文件結構如下
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