Format numbers using bash?
I am trying to find a way to convert large numbers into comma separated numbers using bash. I.e. 12345 -> 12,345 I tried using the printf solution: printf "%'d\n" 12345678 but it doesn't seem to work in Cygwin (probably because locale isn't supported yet). Is there a way to do this within bash?
|
num=12345
echo "${num%???},${num#??}" |
Quote:
|
What exactly are you trying to achieve? How should 12345678 be rendered?
Yves. |
Quote:
Code:
#!/usr/bin/env python Code:
# ./test.py |
Oh I just understood! In most of the world (or so I've read), and at least where I live, the comma stands for the decimal separator. I suppose “your” comma is a thousands separator, isn't it?
Yves. |
In the English speaking world your 2nd sentence is the case :)
PS re OP: That does work in bash: printf "%'d\n" 12345678 12,345,678 |
Quote:
1 = 1 10 = 10 100 = 100 1000 = 1,000 10000 = 10,000 100000 = 100,000 1000000 = 1,000,000 etc. |
I think this will do the trick for you, unless your Cygwin doesn't have sed or, possibly, GNU sed:
Code:
$ echo " 1234567890 " | sed -r ':L;s=\b([0-9]+)([0-9]{3})\b=\1,\2=g;t L' Anticipating your Q's: http://www.gnu.org/software/sed/manual/sed.html ":L": http://www.gnu.org/software/sed/manu...mming-Commands "-r": http://www.gnu.org/software/sed/manu...02dextended-30 "\b": http://www.gnu.org/software/sed/manual/sed.html#Escapes "=": http://www.gnu.org/software/sed/manu...s_0022-Command (para 1) :D :D :D (Cheshire Cat imitation) |
Bravo sir, that works perfectly. It will take me a while to wrap my head around though :p. Thank you very much.
|
You're welcome.
As to "wrapping your head around it", I figured it might be unfamiliar which is why I gave all the links. I'll be happy to answer any specific Q's. |
The above did not work on my PowerMac running Tiger 10.4.11,
So I spent a few minutes to find the solution below. Since my Mac only allows Basic Regular Expression (BRE), I had to change a few things and add a few backslashes to escape the control characters:
Code:
echo "1234567890" | \ and the limit of 19 for the first RE can be changed to the maximum number of digits you may encounter. I haven't tried this on ubuntu yet but it should work for any system that accepts BRE's (and has sed). To see how the command works, remove the branch (t) command. You'll see that the first iteration puts the last (rightmost) comma in. Each successive loop matches the left portion of the number without commas. The last loop exits because there's nothing left to match. |
Quote:
|
turtlegeek,
Welcome to LQ -- good 1st post.
Reuti, Thanks for your suggestion. My tested updated ver.: Code:
echo "1234567890" | \ |
acc-dupe trying to edit.
|
All times are GMT -5. The time now is 01:02 AM. |