CSV 如何使用 UNIX 将多列中的值修剪为 2 个位置

Ash*_*ish 3 sed text-processing csv

示例文件结构如下

Product,Base_Price,Promotion_Price,Discount
Shampoo,1.999999,1.409999,15.9988999
Biscuit,2.999999,2.409999,15.9988999
Run Code Online (Sandbox Code Playgroud)

输出文件应采用以下格式:

Product,Base_Price,Promotion_Price,Discount
Shampoo,1.99,1.40,15.99
Biscuit,2.99,2.40,15.99
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 8

在带有 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
Run Code Online (Sandbox Code Playgroud)

如果您想要传统的 IEEE 从零舍入,请省略该--round=down指令。


ter*_*don 5

这可以满足您的要求:

$ 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
Run Code Online (Sandbox Code Playgroud)

或者,如果您想对数字进行四舍五入而不是仅仅删除多余的数字,您可以尝试:

$ 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
Run Code Online (Sandbox Code Playgroud)