Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org in linux bash how can i calculate the sum of the figures in a number?
 Linux - Newbie This Linux forum is for members that are new to Linux. Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices

 01-13-2014, 12:30 PM #1 rivelino90 LQ Newbie   Registered: Jan 2014 Posts: 6 Rep: in linux bash how can i calculate the sum of the figures in a number? for example number 45 4+5=9
 01-13-2014, 12:38 PM #2 druuna LQ Veteran   Registered: Sep 2003 Posts: 10,532 Blog Entries: 7 Rep: Here's one way: Code: `echo "45" | awk 'BEGIN{FS=""}{for (i=1;i<=NF;i++)x+=\$i}END{print x}'` 3 members found this post helpful.
 01-14-2014, 09:36 AM #3 jpollard Senior Member   Registered: Dec 2012 Location: Washington DC area Distribution: Fedora, CentOS, Slackware Posts: 4,713 Rep: For fun: Code: ```sum=0 while read -n 1 V; do let sum=sum+V done <
 01-14-2014, 09:50 AM #4 schneidz LQ Guru   Registered: May 2005 Location: boston, usa Distribution: fc-15/ fc-20-live-usb/ aix Posts: 5,150 Rep: ^ -1 druuna and jpollard... smells like homework and the op made no attempt. 1 members found this post helpful.
 01-14-2014, 10:08 AM #5 druuna LQ Veteran   Registered: Sep 2003 Posts: 10,532 Blog Entries: 7 Rep: ^ -2 schneidz - late to the party, - not constructive. Also: You, schneidz, should point your remark at the OP and not those that answered. Most people that are new did not read the LQ rules and they don't have a clue what your remarks is about. The people that answer should know about the "homework rule", but it is also up to them to decide if it is homework or not, which isn't always clear. Last edited by druuna; 01-14-2014 at 11:20 AM. Reason: Added some constructiveness. 2 members found this post helpful.
 01-14-2014, 12:06 PM #6 grail LQ Guru   Registered: Sep 2009 Location: Perth Distribution: Manjaro Posts: 9,552 Rep: Well we could tidy the bash up a little: Code: ```while read -n 1 V; do (( sum += V )) done<<<\$1 echo \$sum``` 1 members found this post helpful.

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is Off HTML code is Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post sumeet inani Linux - Newbie 7 04-09-2013 07:46 PM TheIndependentAquarius Programming 16 06-16-2010 02:36 AM thewebbie Programming 1 05-20-2009 12:42 PM paulBottomley Linux - Newbie 5 04-25-2008 01:19 PM a1phanumeric Linux - Newbie 1 11-15-2007 12:29 PM

LinuxQuestions.org

All times are GMT -5. The time now is 05:34 AM.

 Contact Us - Advertising Info - Rules - LQ Merchandise - Donations - Contributing Member - LQ Sitemap -