Substring

Hi All,

In ksh, am trying to get a substring stuff done. Not sure where the problem is.. can you guys guide me on this...
for instance, var1=41, and var2=4175894567, then i want to know whether var2 starts with var1.. var1 and var2 can be of any length..

VAR1=41
VAR2=419068567777
VAR3=1
VAR4=118858488490000
VAR1LEN=`echo ${#VAR1}`
VAR3LEN=`echo ${#VAR3}`
echo $VAR1LEN
echo `${VAR2:0:`echo ${#VAR1}`}` - tried multiple combinations here.. nothing worked.. doesn't it accept expressions in it..?

Thanks in advance!

Using parameter expansion in bash or ksh

VAR1=41
VAR2=419068567777
[ $VAR1 -eq ${VAR2:0:${#VAR1}} ] && echo OK || echo NOK
1 Like

Plain ksh or pdksh can't do this kind of parameter expansion. It could be ksh93 can do it but I didn't try. bash can do it. You could instead use something like:

$> VAR1=41
$> VAR2=419068567777
$> if [[ $VAR1 == $(echo $VAR2| cut -c 1-${#VAR1}) ]]; then echo same; else echo different; fi
same
1 Like

Thanks zaxxon. One more query.. how to drop that VAR1 from var2 and get the rest of the stuffs from VAR2.

VAR1=41
VAR2=419068567777
VAR2=${VAR2#${VAR1}}
echo $VAR2
9068567777
1 Like

It worked.. Thanks!.. Can you please share a link where i can learn more about trimming..
Thanks!

The man page of bash on my Debian Linux box has a good documentation about that topic "parameter expansion", while the AIX ksh man page is somewhat scarce for this.

On the web just google for "shell parameter expansion" or exchange shell vs. ksh or bash.

1 Like