Numbers with leading zeros

Hi,

i have a variable which conatins values like 00001,0003,00067,00459.
I want to use the values one by one and in the same form as they are like 00001,0003,00067,00459.

Also can anyone tell me how to increment those numbers by 1,keeping the format as same like 00002,0004,00068,00460.
Pls suggest how to do.:wall:

u can try below..

 
echo "00001,0003,00067,00459"|awk -F, '{for(i=0;i<=10;i++){printf "%05d,%05d,%05d,%05d\n",++$1,++$2,++$3,++$4}}'

You can't have both. Either you treat the variable as string, then leading zeroes can be retained, but you can't increment, or you treat it as a numeric variable, allowing for increments, but losing leading zeroes. What you can do is using a formated print as @vidyadhar85 suggested to convert your incremented numeric into a string with leading zeroes.

Using ksh shell:

 
#/bin/ksh
 
var=00001,0003,00067,00459
 
typeset -Z -R05 arr v
 
set +A arr $(echo $var | sed 's/,/ /g')
 
# array arr contains variables
 
for v in ${arr[@]}
do
  (( v = v + 1 ))
  echo $v
done

Result:

 
00002
00004
00068
00460

Try this:

$ echo "00001,0003,00067,00459" | nawk -F, '{for(i=1;i<=NF;i++){s="0000"$i+1;print substr(s,length(s)-length($i)+1)}}'
00002
0004
00068
00460

If x is a shell variable whose value is a zero-padded integral string of some unspecified width, the following will increment the value, preserving padding/width so long as the value does not exceed the range representable with the initial quantity of digits:

printf "%0${#x}d\n" $((10#$x+1))

That should work with ksh88, ksh93, pdksh, and bash (and probably others).

Regards,
Alister

1 Like