Operating System - HP-UX
1827444 Members
5891 Online
109965 Solutions
New Discussion

Re: ksh script, compare two variables

 
Stack
Occasional Advisor

ksh script, compare two variables

I've done this before in ksh, but I can't remember how.

Suppose I have a variable, $str, that contains a bunch of text. I have another variable, $substr, that contains some other text.

I need to contruct a test to see if $str "contains" $substr. The trick is, I need to do this with builtins only, no awk, grep, etc.

I recall something with parameter expansion, like testing if ${str%$substr} = $substr....

Help!
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: ksh script, compare two variables

Hi:

Take a look at the man pages for 'sh-posix'. You will see shell built-in pattern matching like:

${parameter##pattern}
${parameter%%pattern}

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: ksh script, compare two variables

Hi (again):

...and I should add that the Posix shell ('/usr/bin/sh' or '/sbin/sh') is really a superset of the Korn shell ('/usr/bin/ksh').

Hence you could look at either the man pages for 'sh-posix' or those for 'ksh' for more explanation of the shell pattern matching.

Regards!

...JRF...
Stack
Occasional Advisor

Re: ksh script, compare two variables

I've got it. To test to see if $substr is contained in $str, you could use:

[[ "${str%${substr}*}" != "$str" ]] && echo $substr is within $str

harry d brown jr
Honored Contributor

Re: ksh script, compare two variables

Stack,

good catch! too bad you can't give yourself a ten pointer :-)

One big question, why don't you want to use "normal" pattern matching features like grep, awk, sed, perl ??

live free or die
harry
Live Free or Die
Stack
Occasional Advisor

Re: ksh script, compare two variables

Harry,

Yeah, I knew I was close, I just had to think about it a while. The problem with using sed/awk/grep/etc is the performance hit.

I'm doing Timefinder scripting on an EMC Symmetrix, and I'm trying to get the run time of the script down as low as possible. We're doing Timefinder splits on a live Informix database (7.3), and the way Informix supports this is to temporarily block writes to disk. Needless to say, I want to make sure Informix blocks the writes for as short a period as possible.

I've done this in the past (non-grep/etc string compares in ksh), and using the ksh builtins is a HUGE performance boost. If you're looping through arrays, and have a lot of searches/compares to do, the grep's can add up...

Scott Riley
Stack Computer, Inc.