LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   append integers until total is x integers (https://www.linuxquestions.org/questions/linux-newbie-8/append-integers-until-total-is-x-integers-4175497851/)

razorcbl 03-11-2014 06:48 PM

append integers until total is x integers
 
Working on a basic bash and i would like to have a check (if statement?) to make sure this variable is always 9 integers long..and if it is not then append 0 until it is.

sometimes this variable is: 123456789 (do nothing)
but if its: 123456 append '0' until its 123456000

I have searched online and this forum but cant seem to find the correct way to do this (looked at "if" statements").


Thanks in advance

Beryllos 03-11-2014 07:03 PM

Take a look at this:
http://tldp.org/LDP/abs/html/comparison-ops.html
and remember that every 9 digit number is -ge 100000000 and -lt 1000000000

Beryllos 03-11-2014 07:23 PM

To append zeroes, multiply by 10. Take a look at this:
http://www.tldp.org/LDP/abs/html/ops.html
There are various bash methods that work (see Example 8-2). Here are two examples:
Code:

$ a=5
$ ((a=10*a))
$ echo $a
50
$ let "a=a*10"
$ echo $a
500
$


grail 03-11-2014 10:24 PM

Whilst the forum and google have let you down, the general rule is you at least show your attempt and then we can assist.

jpollard 03-12-2014 11:12 AM

Look like it would be simpler to just append a string of 9 0's ("000000000") then take the substring of the first 9 characters....

Code:

$value = "${value}000000000"
$value = ${value:0:9}


colucix 03-12-2014 11:22 AM

Another one:
Code:

$ var=123456
$ printf "$var%0*d\n" $((9-${#var})) 0
123456000


Shadow_7 03-12-2014 11:35 AM

If you know that the integers will never be > 9 chars. Append 0's and chop the first 9 off.

$ echo $VAR"000000000" | head -c 9

Plus the previous bash way mentioned. Each with it's quirks. I've seen version issues where -c # for head / tail can be +/- 1 depending on distro and version. And the bash substring doesn't work on other shells like debians default shell dash.

jpollard 03-12-2014 02:29 PM

Quote:

Originally Posted by Shadow_7 (Post 5133334)
If you know that the integers will never be > 9 chars. Append 0's and chop the first 9 off.

$ echo $VAR"000000000" | head -c 9

Plus the previous bash way mentioned. Each with it's quirks. I've seen version issues where -c # for head / tail can be +/- 1 depending on distro and version. And the bash substring doesn't work on other shells like debians default shell dash.

True - but you should still be able to use
Code:

res = `expr substr "${var}00000000" 0 9`
for the same result.


All times are GMT -5. The time now is 12:04 AM.