views:

68

answers:

2

Hello,

Is there easy way how to round floating numbers in a file to equal length? The file contains other text not only numbers.

before: bla bla bla 3.4689 bla bla bla 4.39223 bla.
after:  bla bla bla 3.47 bla bla bla 4.39 bla.

Thanks

+4  A: 

Bash

#!/bin/bash
shopt -s extglob
while read -r line
do
  set -- $line
  for((i=1;i<=${#};i++))
  do
    s=$(eval echo \${${i}})
    case "$s" in
     +([0-9]).+([0-9]) ) s=$(printf "%.2f " $s);;
    esac
    printf "%s " $s
  done
  echo
done <"file"

output

$ cat file
bla1 bla 2 bla 3.4689 bla bla bla 4.39223 bla.
words ..... 2.14 blah blah 4.5667 blah

$ ./shell.sh
bla1 bla 2 bla 3.47 bla bla bla 4.39 bla.
words ..... 2.14 blah blah 4.57 blah
ghostdog74
Are you by any chance Steve bourne :) You look like shell super guru.. ++ btw :)
gameover
A: 

awk BEGIN{RS="[[:space:]]"} /[0-9].[0-9]/{printf("%.2f%s",$1,RT)} !/[0-9].[0-9]/{printf("%s%s",$1,RT)} f.txt

You might want to change RS to something that can handle a more robust set of word boundaries. This solution has the advantage of preserving the boundary rather than just reprinting the output separated by spaces.

frankc