String increment in UNIX

Hi,

I am able to increment numbers but unable to increment the charters in unix -AIX.

Source : AAA BB CCC
Increment Number : 5

OUTPUT:

AAA BB CCC
AAA BB CCD
AAA BB CCE
AAA BB CCF
AAA BB CCG

Thanks
onesuri

What are "the charters in unix"?

What comes after AAA BB CCZ? (AAA BB CC0, AAA BB CCa, AAA BBB CC[, AAA BB CD0, AAA BB CDa, or something else?) What characters are included in the character set for this exercise and in what order do they appear?

Try this bash solution (assuming AAA BB CDA comes after AAA BB CCZ and AA comes after Z):

#!/bin/bash
S="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function inc
{
    local I F B
    F=${1%?}
    B=${1#$F}

    case "$B" in
       (\ ) echo "$(inc "$F") " ;;
       (Z) [ -z "$F" ] && echo AA || echo "$(inc "$F")A" ;;
       (*) echo "$F${S:1+36#$B:1}"
    esac
}

read -p "Source : " src
read -p "Increment Number : " cnt

for((i=0;i<cnt;i++)) {
    echo "$src"
    src=$(inc "$src")
}

Here's another solution in bash:

#!/bin/bash
#
#
#

# check command-line for filename and
# number to increment by
if [ $# -ne 2 ]
then
    echo "Usage: ${0##*/} \"<string>\" <increment #>"
    exit 1
fi

# store the values
str=$1
i=$(expr $2 + 1 )

# loop through file and increment last character
echo $str
for((x=1;x<$i;x++))
do
    lastChar=$(echo $str | awk '{print substr($0,length($0),1)}')
    incrLetter=$(echo $lastChar | tr 'A-Y' 'B-Z')
    newStr=$(echo $str | sed "s/.$/$incrLetter/")
    echo $newStr
    str=$newStr
done

# done
exit 0

./incAlpha.sh "AAA BB CCC" 5
AAA BB CCC
AAA BB CCD
AAA BB CCE
AAA BB CCF
AAA BB CCG
AAA BB CCH

289e80450dacb315df8e7ae3eaf1ed3d

#!/bin/ksh93

function incstring
{
   src=$1

   typeset -i len=${#src}
   max=$(( len - 1))

   new=""
   typeset -i dec 
   carry=0

   while ((len--))
   do
      last=${src:$len:1}
      dec=$(printf "%u" "'$last")
      (( dec != 32 )) && {
         (( len == max )) && (( dec++ ))
         (( carry == 1 )) && { (( dec++ )); carry=0; } 
         carry=0
         (( dec > 90 )) && { dec=65; carry=1; } 
      } 
      ascii=$(printf \\$(($dec/64*100+$dec%64/8*10+$dec%8)))
      new=${ascii}${new}
   done

   echo $new
}


read str?"Source: "
read cnt?"Count: " 

for ((i=0; i < cnt; i++)) {
    str=$(incstring "$str")
    echo $str
}

1 Like

@fpmurphy - Nice solution, I like the shell conversion to dec I haven't come across that before.

A slight tweak is probably required to ensure that "ZZ" increments to "AAA":

   ((carry)) && new="A$new"
   echo $new