views:

326

answers:

3

How do I check a int variable ($inputNo) to see if it’s 2 or more decimal digits long?

Example:

inputNo="5"

Should be changed to: 05

inputNo="102"

Should be left alone: 102

I thought about using wc and if statements, but wc -m doesn’t seems to give the actual characters passed into wc, as wc always seems to give +1 to the characters that is given.

But I don’t know how to add a 0 in front of the current input number.

+1  A: 

You can use http://bash-hackers.org/wiki/doku.php/commands/builtin/printf, an example from there:

the_mac="0:13:ce:7:7a:ad"

# lowercase hex digits
the_mac="$(printf "%02x:%02x:%02x:%02x:%02x:%02x" 0x${the_mac//:/ 0x})"

# or the uppercase-digits variant
the_mac="$(printf "%02X:%02X:%02X:%02X:%02X:%02X" 0x${the_mac//:/ 0x})"
The MYYN
Thanks for the link, I always like to read how a function works and what it can all do.
Mint
+7  A: 

Just use the printf command to change the variable, based on the format string:

pax> export inputNo=5
pax> inputNo=$(printf "%02d" $inputNo) ; echo $inputNo
05
pax> export inputNo=102
pax> inputNo=$(printf "%02d" $inputNo) ; echo $inputNo
102

You'll want to make sure it's numeric first otherwise the conversion will fail. If you want to be able to pad any string out to two or more characters, you can also use:

while [[ $(echo -n ${inputNo} | wc -c) -lt 2 ]] ; do inputNo="0${inputNo}"; done

which is basically a while loop (using echo -n which doesn't output the newline as well, which is what was skewing your character count) which prefixes "0" until the length is right.

paxdiablo
Thanks! Works great.
Mint
No need for external processes in the general case: `while test "${#inputNo}" -lt 2; do inputNo="0$inputNo"; done` (*[[* changed to *test* with added quoting to make it compatible with more shells).
Chris Johnsen
No need for bash extensions (${#...}) either: `case $inputNo in [0-9]) inputNo="0$inputNo";;*);;esac`.
Idelic
${#…} is not really bash-specific. It is part of the POSIX shell spec (http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02), though it is not present in the authentic Bourne shell (http://heirloom.sourceforge.net/sh/sh.1.html#5).
Chris Johnsen
+2  A: 

For general-purpose padding whether the string is numeric or not

No need for piping echo into wc or using a while loop.

In Bash, you can get the length of a string like this: ${#inputNo}.

And since you can do substrings, you can do this instead:

if [[ ${#input} < 2 ]] 
then
    inputNo="00${inputNo}"
    inputNo="${inputNo: -2}"
fi
Dennis Williamson