I have number/strings like below
input =23412133
output = 234121330000 (depends on the number give at runtime)
i need to padd zeros based on runtime input . i tried below
printf ' %d%04d\n', "23412133";
But the precision 4 is static here how can i pass this as runtime input.
i am using this is shell script
Adding zeros to the end of a number changes its value, so printf isn't set up to do that.
Could you be more clear on your requirements, do you want to know how to use arguments within a script/function $1 $2...
or are you wondering how to add orders of magnitude to an integer?
how many zeroes you need to add at the end..?
if it is 4 always then simply multiply that no. by 10000 and then print.
i have shell script
While <read file>
do
ecode=`echo $line | cut -d"|" -f4`
length=`echo $line | cut -d"|" -f5`
example ecode will have
34628
23492759
523489573
156232
123414
1233
length=10
output
3462800000
2349275900
i need to append zeros at the end of the each based on the length field
go with this ..
$ z=10
$ echo "1234 * 10^$z" | bc
12340000000000
try this:
$tmp=$ecode;
$count=0;
while($tmp>0)
{ $tmp=$tmp/10; $count++; }
$output=$ecode*10^($length-$count);
print $output;
This works for padding zeros ... if i want to append any other character ?
example
12121
i want to append zero and nine's
1212100000 1212199999
Traditional way!
echo 12121 | awk '{printf $0;while(len-->0){printf char}}' len=5 char=9
HTH
--ahamed
1 Like
if you want mathematical code then here it is:
$tmp=$ecode;
$count=0;
while($tmp>0)
{ $tmp=$tmp/10; $count++; }
$output=$ecode;
$character=9;
for($i=0;$i<$length-$count;$i++)
{ $output=$output*10+$character; }
print $output;
If your using bash you could setup some functions:
#!/bin/bash
function fill
{
# fill string to width of count from chars
#
# usage:
# fill [-v var] count char
#
# if count is zero a blank string is output
FILL="${2:- }"
for ((c=0; c<=$1; c+=${#FILL}))
do
echo -n "${FILL:0:$1-$c}"
done
}
function pad
{
# Pad to right of string to required width, using chars.
# Chars is repeated, as required, until width is reached.
#
# usage:
# pad [-v var] width string <chars>
#
# if chars not specified spaces are used
BACK=$(fill $1 "$3")
let PAD=$1-${#2}
if [ $PAD -lt 1 ]
then
echo -n ${2:0:$1-1}
else
echo -n "$2${BACK:${#2}}"
fi
}
echo $(pad 10 12121 0) $(pad 10 12121 9)
echo $(pad 10 12121 "-.")
echo $(pad 10 12 "-.")
Output:
1212100000 1212199999
12121.-.-.
12-.-.-.-.
The Perl way.
$ echo "123" | perl -e 'chomp($x=<>);$pad_chr="0";$len=3; print $x . ($pad_chr x $len)'
123000
Sans redundance.
$ echo "123" | perl -e 'chomp($_=<>);print $_ .("0"x3)'
123000
1 Like
its grt ... Thx for all ur help...
it worked