Results 1 to 7 of 7
I'M trying to write a small program that will take a number as input, anything from 1 to 999,999,999,999 and return it as a string. I've already created a flowchart ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 12-26-2012 #1Linux Newbie
- Join Date
- Dec 2010
- Posts
- 110
NumberSting bash program
I'M trying to write a small program that will take a number as input, anything from 1 to 999,999,999,999 and return it as a string. I've already created a flowchart in dia and now I'M trying to write on top of that chart in bash. I'M very new to bash by the way.
The first thing I need to do is recieve the number a figure out how many groups of three are in the number. Based on counting by threes, if there's an odd number like 4 or 5 that still need t ocount as a groupd. Examples: ### = 1 groups, #,### = 2 gropus, ##,### = 2 groups.
I think I need to dived by 3 what the answer will be my number but I need to account for the remainders as well. Any advice? Thanks.
- 12-26-2012 #2Trusted Penguin
- Join Date
- May 2011
- Posts
- 3,664
Hi,
To get the number in bash, you can either provide the number as a command line argument to the script (i.e., you provide it when you call the script), or you can pass it via STDIN (using the bash built-in read).
example of the former:
call it like this:Code:#!/bin/bash foo=$1 echo "You said '$foo'"
example of the latter:Code:./script.sh 1,234
call it like this:Code:#!/bin/bash read -p "Enter a number: " foo echo "You said '$foo'"
Note that you'll want to verify that $foo is a number, before going any further (i.e., use a grep regex).Code:./script.sh
To determine how many groups are in the number, you could either count the commas using grep and the "-c" option (assuming they are provided), or just use bash built-in arithmetic (e.g., if [ $foo -gt 999 ]; then) to see if the number is greater than 999 or 999,999, etc.
- 12-26-2012 #3Linux Newbie
- Join Date
- Nov 2012
- Posts
- 134
how are given numbers? with or without coma?
with comas:
- put the number in a variable
- replace every coma by a space
- put the "new" variable into an array
- see how many items has got the array
without comas, you need to divide the number of digits in the number by three, and add one if the modulo is more than zero.Code:var=10,000,000 array=( ${var//,/ } ) echo ${#array[@]}
Code:var=1,000,000 echo "$(( (${#var} % 3 ?1:0) + (${#var}/3) )) group(s)"
- 12-26-2012 #4Linux Newbie
- Join Date
- Dec 2010
- Posts
- 110
- 12-26-2012 #5
You might want to have a look at printf and the radix character.
Code:man 1 printf man 3 printf
You must always face the curtain with a bow.
- 12-26-2012 #6Linux Newbie
- Join Date
- Dec 2010
- Posts
- 110
What is ?1:0 and what is group? Is group a bash keyword?
- 12-26-2012 #7Linux Newbie
- Join Date
- Nov 2012
- Posts
- 134
see ternary operator
and
man bash arithmetic evaluation


Reply With Quote

