convert 1012345601 to $10,123,456.01


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers convert 1012345601 to $10,123,456.01
# 8  
Old 04-16-2008
Hi.

Here is a short perl script, but note that it will fail on numbers that contain decimal points:
Code:
#!/bin/bash -

# @(#) s1       Demonstrate commify for signed integer strings in perl.

echo
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version =o $(_eat $0 $1) perl
echo

rm -f t1

cat <<'EOF' |
999
1000
+1000
-1000
999.999
1000.1234
We saw $25000 in the cash box.
EOF
perl -wpe '1 while s/(\d+)(\d\d\d)/$1,$2/;'

exit 0

Producing:
Code:
% ./s1

(Versions displayed with local utility "version")
Linux 2.6.11-x1
GNU bash 2.05b.0
perl 5.8.4

999
1,000
+1,000
-1,000
999.999
1,000.1,234
We saw $25,000 in the cash box.

This is similar to the code found in the Perl Cookbook, and at several places on the net. It has the advantage of being to able to do the work without extracting the integer string -- if something doesn't look like an integer, it skips over it. It will not skip leading zeros, nor add the $ for you -- just basic comma insertion.

There are pure shell functions that can do the same thing. Balancing the sizes of the codes and the size of the interpreters, I'd usually chose the sed solution. However, if one is doing something in awk or perl, one can use these methods directly in the code. I like the brevity of the perl script, made possible by regular expressions.

Additional perl solutions can be found the recent thread converting number representation - LinuxQuestions.org ... cheers, drl
 
Login or Register to Ask a Question

Previous Thread | Next Thread

3 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How to grep a pattern having value greater than 123 in a file?

Hi, I have a dynamically growing ascii file which has large data (both text and digits). I need to grep those lines having value greater than '123'. These numeric values may appear at anywhere in the line, hence I could not use awk to split to columns. So, please help me with the grep regular... (12 Replies)
Discussion started by: royalibrahim
12 Replies

2. Shell Programming and Scripting

Increment ABC-123 by 1!!

in a shell script, i hav a variable declared as "ABC-123". i want to incriment th value ABC-123 by 1 so that the result will be ABC-124. Can anyone suggest a solution in shell scripting.. (4 Replies)
Discussion started by: pgmfourms
4 Replies

3. Shell Programming and Scripting

to make 1 2 3 into 123

suppose u have a file ABC ADFA AFAF AGBA AHHAH AJJA AJKA AJAJ AJAJA AJAJAJ AHAB AAAJ AJAJA AKK AJAJAA means gaps have to replaced and see also there will be gaps so output shud be ABCADFAAFAFAGBAAHHAHAJJAAJKAAJAJAJAJAAJAJAJAHABAAAJJAJAAKKAJAJAA Thanks (2 Replies)
Discussion started by: cdfd123
2 Replies
Login or Register to Ask a Question