Marjer
Marjer

Reputation: 1403

remove trailing zero using awk

I have the following values in my file:

1.5000
 0.006
 9.0001
 104.2500
 17.0000
 3.5000

I want to remove the trailing zero, the following awk will reove the trailing zeros

awk '{ if ($0 ~ /\./){ sub("0*$","",$0); sub ("\\.$","",$0);} print}' file

Output of above awk,

1.5
 0.006
 9.0001
 104.25
 17
 3.5

But I want to add a single zero after the decimal point, I.e. All I want is a float number without trailing zero except values like, 2.0, 3.0

Excepted output

1.5
 0.006
 9.0001
 104.25
 17.0
 3.5

Upvotes: 1

Views: 4066

Answers (4)

mklement0
mklement0

Reputation: 437218

Use of sed is probably simpler in this case:

Note:

  • The following uses sed with -E (alias of -r) to enable support for extended regular expressions, which makes the command more readable. It should work with GNU sed (Linux) and FreeBSD sed (OSX).
  • Uses a single substitution command (s/.../.../).
  • Should there be integers in the input, they are left untouched.
sed -E 's/^( *[0-9]+\.[0-9]([0-9]*[1-9])?)0+$/\1/' file
  • ^ at the beginning and $ at the end ensure that the entire input line is matched
  •  * matches leading spaces, if any
  • [0-9]+\. matches all digits before the decimal point, plus the decimal point
  • [0-9] matches the first decimal place (a single digit) - this ensures that a number ending in .0 isn't stripped of its trailing 0
  • ([0-9]*[1-9])? matches any additional digits until a nonzero digit is encountered, if any
  • 0+ then captures trailing zeros through the end of the line
  • in the replacement string, \1 refers to the 1st capture group ((...)), which is everything except the trailing zeros - effectively removing them.
  • Note that due to seds default behavior of outputting all lines - whether modified or not - lines without matching numbers (numbers that didn't need modification) are simply passed through.

Upvotes: 1

Sadhun
Sadhun

Reputation: 264

Use the below command for more accurate output,

Filename : sam

cat sam

45.0005
0.4440000
45.000000
66.66
44.000
.45000
45
 awk '{if($0 ~ /^[0-9]*\.[0-9]+/) { sub(/0+$/,"") sub(/\.$/,".0") sub(/^\./,"0.");} else if($0 ~ /^[0-9]+$/) {sub(/$/,".0");}}1' sam

Output:

45.0005
0.444
45.0
66.66
44.0
0.45
45.0

Upvotes: 0

Jotne
Jotne

Reputation: 41456

New version that handles better long numbers and text

cat file
1.5000
0.006
 9.0001
 104.2500
17.0000
 3.5000
450.0005
test
my00000

awk '/^ *[0-9]+\.[0-9]+/{sub(/0+$/,"");sub(/\.$/,".0")}1' file
1.5
0.006
 9.0001
 104.25
17.0
 3.5
450.0005
test
my00000

This replace all leading 0 with nothing. If you get . at final, replace it with .0
It also test if its start with 0 or more space, than number.

Upvotes: 0

choroba
choroba

Reputation: 241808

Possible with sed:

sed 's/0\+$//;s/\.$/.0/'

If integers like 1200 can occur in the input, handle them separately:

sed '/\./{s/0\+$//;s/\.$/.0/;b};s/$/.0/'

Upvotes: 1

Related Questions