I am passing input string,length, and the pad character.
input string=123
Pad char=#
Length=6
then the output should be:
###123
How we can do this?
Thanks
I am passing input string,length, and the pad character.
input string=123
Pad char=#
Length=6
then the output should be:
###123
How we can do this?
Thanks
awk, perl, c, or shell (if shell, which shell?) ?
AWK or KSH.
#!/bin/ksh
lpad()
{
if [ $# -eq 3 ] ; then
echo "$1" | awk -v pad="$2" -v len=$3 '{
if(length($0) >= len) {print $0; exit}
for(i=0;i<len - length($0);i++) { tmp=tmp pad }
print tmp $0 }'
else
echo "Invalid parms for lpad" > 2
fi
}
# usage / test
val=$(lpad "test string" "0" 14); echo "$val"
val=$(lpad 1234 "#" 4); echo "$val"
val=$(lpad 1234 "#" 8); echo "$val"
Here is a solution using pure ksh - it's much bigger that the version that spawns awk but you do get substr() and fill() functions at no extra cost:
substr() {
# string start [length]
str="$1"
start=$(( $2 ))
let end=${#str}-$start-$(( ${3:-9999} ))+1
[ $start -gt ${#str} ] && return
for chop in "??????????" "????" "?"
do
while [ $start -gt ${#chop} ]
do
str="${str#$chop}"
let start=start-${#chop}
done
while [ $end -ge ${#chop} ]
do
str="${str%$chop}"
let end=end-${#chop}
done
done
printf "$str"
}
fill() {
# fill count [chars]
FILL="${2:- }"
chars=$(( $1 ))
c=0
while [ $c -le $chars ]
do
printf "%s" "$(substr "$FILL" 1 ${chars}-$c )"
let c=c+${#FILL}
done
}
lpad() {
# lpad width string [chars]
let PAD=$1-${#2}
if [ $PAD -lt 1 ]
then
substr "$2" 1 $1-1
else
fill $PAD "$3"
printf %s "$2"
fi
}
#and now some tests
echo $(lpad 14 "test string" ".-")
echo $(lpad 4 1234 "#")
echo $(lpad 8 1234 "#")
output:
.-.test string
123
####1234
@pandeesh: Try Perl.
perl -e '$str="123";$pad="#";$len=3;print (($pad x $len) . $str)'
Just a funny note. No offense intended ![]()
Master Foo and the Ten Thousand Lines