Operating System - HP-UX
1752625 Members
4548 Online
108788 Solutions
New Discussion юеВ

Re: shell scripting - test for similarity

 
SOLVED
Go to solution
Omar Alvi_1
Super Advisor

shell scripting - test for similarity

Hi,

how does one test for similarity in shell scripting? "If" doesn't seem to accept wildcards.

I want something like, if the string is similar to Lo1, Lo2, Lo, then do something

I tried

if
[ $string = Lo* ]
then
exit

Its simple in perl, but here I have a shell script to modify.

-Alvi
8 REPLIES 8
Vibhor Kumar Agarwal
Esteemed Contributor

Re: shell scripting - test for similarity

Try putting it in double quotes (")
Vibhor Kumar Agarwal
Rajesh SB
Esteemed Contributor
Solution

Re: shell scripting - test for similarity

Hi Omar,

You use "case" statement instead of "if-then".

case $string in
Lo1) execute
;;
Lo2) execute1
;;
L0*) execute2
;;
A|a) execute3;;

*) execute4
;;
esac
Hope this server your purpose.

Regards,
Rajesh SB
Chan 007
Honored Contributor

Re: shell scripting - test for similarity

Why not try

if [ $String = Lo1 ] && [ $string = Lo2 ]

Chan


Warren_9
Honored Contributor

Re: shell scripting - test for similarity

hi,

for wildcard, use the "case" instead of "if-then".

GOOD LUCK!!
Vibhor Kumar Agarwal
Esteemed Contributor

Re: shell scripting - test for similarity

Why dont' you use the substring function of if.

I dont' remember how its exactly written.
Check out the man pages.
Vibhor Kumar Agarwal
john korterman
Honored Contributor

Re: shell scripting - test for similarity

Hi Alvi,

you can grep for a pattern at the beginning of a string, e.g.:

#!/usr/bin/sh
PAR="$1"
PATTERN="Lo"
echo "$1" | grep -q ^"$PATTERN"
if [ $? = "0" ]
then
echo hit
else
echo no hit
fi

try the above with your string to compare as $1


regards,
John K.
it would be nice if you always got a second chance
Rodney Hills
Honored Contributor

Re: shell scripting - test for similarity

The single [] uses the command test (do man test). The [[]] uses a conditional tester that is part of ksh/posix-sh. Try with the 2 square bracket test-

if [[ $string = Lo* ]]
then
exit

HTH

-- Rod Hills
There be dragons...
Omar Alvi_1
Super Advisor

Re: shell scripting - test for similarity

Thank you all for the suggestions.

The case and grep ideas worked perfectly. The if substring thing, though, I didn't get.

And Rodney, the double square brackets, exactly what I was looking for.

Thanks and Regards,

-Alvi