Saturday, November 13, 2021

[SOLVED] Remove useless .0 from txt files in bash

Issue

How can I remove useless ".0" strings in a txt file of numbers?

If I have this file:

43.65 24.0 889.5 5.0
32.14 32.0 900.0 6.0
38.27 43.0 899.4 5.0

I want to get:

43.65 24 889.5 5
32.14 32 900 6
38.27 43 899.4 5

I tried: sed 's|\.0 | |g' but that obviously does not work with new lines and EOF.

Any suggestion without getting into python, etc?


Solution

You can use

sed -E 's,([0-9])\.0($| ),\1\2,g' file

Details:

  • -E - enables POSIX ERE syntax
  • ([0-9])\.0($| ) - finds and captures into Group 1 a digit, then matches .0, and then matches and captures into Group 2 a space or end of string
  • \1\2 - replaces with Group 1 + Group 2 concatenated values
  • g - replaces all occurrences.

See the online demo:

s='43.65 24.0 889.5 5.0
32.14 32.0 900.0 6.0
38.27 43.0 899.4 5.0'
sed -E 's,([0-9])\.0($| ),\1\2,g' <<< "$s"

Output:

43.65 24 889.5 5
32.14 32 900 6
38.27 43 899.4 5


Answered By - Wiktor Stribiżew