CSV UNIX を使用して複数の列の値を 2 桁にトリミングする方法

CSV UNIX を使用して複数の列の値を 2 桁にトリミングする方法

サンプルファイル構造は以下のとおりです。

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) を使用して数値を小数点以下 2 桁に切り捨てます。

$ 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

関連情報