In a Multi-columnar File - Remove all Trailing 0's from Decimal Numbers in Bash

Viewed 42

Sample Data Below having 2 Lines and Pipe Delimeter-

FD|2020-07-21 05:28:15|+08:00|15953092491000|2020072122001412161425872467|2088411904346062|05|S|2020-07-21 05:28:15|+08:00|2480.000000|CNY|S|在线支付||29.760000|CNY||S|2020-07-21 05:28:15|+08:00|2480.000000|CNY||||||

FD|2020-07-20 15:15:29|+08:00|15952580397320|2020072022001448541422843472|2088411904346062|05|S|2020-07-20 15:15:29|+08:00|1380.000000|CNY|S|在线支付||13.110000|CNY||S|2020-07-20 15:15:29|+08:00|1380.000000|CNY||||||

I was trying to Use below -

sed -r -e 's/\|/||/g' -e 's/(\|[0-9.]+[1-9])0+\|/\1|/g' -e 's/\|\|/|/g' 

But this is also removing the trailing 0's even before decimal like 212000 to 212 , which i dont want.

I want only the trailing 0's after Decimal to be Removed - Example- 72.650000 to 75.65

1 Answers

You may use this sed:

sed -E 's/(\.[0-9]*[1-9])0+(\||$)/\1\2/g; s/\.\0+(\||$)/\1/g' file
FD|2020-07-21 05:28:15|+08:00|15953092491000|2020072122001412161425872467|2088411904346062|05|S|2020-07-21 05:28:15|+08:00|2480|CNY|S|在线支付||29.76|CNY||S|2020-07-21 05:28:15|+08:00|2480|CNY||||||
FD|2020-07-20 15:15:29|+08:00|15952580397320|2020072022001448541422843472|2088411904346062|05|S|2020-07-20 15:15:29|+08:00|1380|CNY|S|在线支付||13.11|CNY||S|2020-07-20 15:15:29|+08:00|1380|CNY||||||

Here:

  • s/(\.[0-9]*[1-9])0+(\||$)/\1\2|/g: Removes trailing zeroes after 1 or more non-zero digits after dot
  • s/\.\0+(\||$)/\1/g: Removes all trailing zeroes after dot
Related