[PLUG] shell formatting of numbers

Paul Heinlein heinlein at madboa.com
Tue Nov 11 09:47:01 UTC 2003


On Tue, 11 Nov 2003, Alice Corbin wrote:

> Try one of these:
>
>  # add commas to numeric strings, changing "1234567" to "1,234,567"
>  gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                     # GNU sed
>  sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds

I'd never seen that cool branching before. Neat. Just goes to show
what someone who knows sed well can do. I had to assign a variable and
write a loop:

  x=9123456789123456789

  while [ $(expr "$x" : '[0-9]*') -gt 3 ]; do
    x=$(echo "$x" | sed 's!\([0-9]\)\([0-9]\{3\}\)\(\.\|,\|$\)!\1,\2\3!')
  done

And I should've used either the word boundary marker or a negated
class ([^0-9]) instead of my "dot, comma, or end-of-string" thingee.

Live and learn.

--Paul Heinlein <heinlein at madboa.com>




More information about the PLUG mailing list