Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
This is probably a very simple question.
I cannot remember what is the shell equivalent for the Like operator.I want to construct a syntax like this:
var=er_non_pstn_output.csv
if $var like '*non_pstn*'
do something
else
do something
fi
Which is to say if the variable var contains the pattern "non_pstn" somewhere, do something.I know the solution is very easy, but simply cannot remember how this is done.
Can anyone help?
-Anukta

Colon of expr command is the like operator. If pattern is not found, it returns zero (and false status), otherwise it returns length of the matching portion and true status. The pattern has an automatic beginning-of-line anchor, and you can optionally put an end-of-line anchor.
expr "$var" : ".*non_pstn"
11if expr "$var" : ".*non_pstn" 2> /dev/null ; then
echo 'Pattern found'
else
echo 'Pattern NOT found'
fi

Thanks James, that worked.
I did notice that it works even without a wildcard character.
if expr "$var":"non_pstn" 2> /dev/null
then
echo PATTERN FOUND
else
echo NOT FOUND
fi
works as well.
-Anukta

Looks like a little problem here:
For the value
var=er_non_pstn_output.csv
expr "$line":".*non_pstn"
pattern matches very well.Which is fine.
But when
var=er_pstn_output.csv
I don't want the pattern match to return true, but it does.
How can I get around this problem?
-Anukta

In ksh there's no "like", you just use "=" with pattern matching:
[[ ${var} = *non_pstn* ]] && print Yep

William,
That seems to work, Thanks a lot.Can you also tell me when do you use a single '[' bracket for comparison and when do you use a double '[['?
-Anukta

[ ] is bourne shell, which ksh supports for backward compatibility. [[ ]] is ksh syntax (also bash). I always use [[ ]].

anukta,
Regarding your little problem, I see two problems. First, you are setting a value for $var but then testing $line. And secondly, that colon needs to be space delimited.In the first example below, expr simply sees a unary string expression and displays the string as is (the shell strips the quotes before expr gets it). The second example finds no match because there is an implied beginning-of-line anchor:
expr abcdefgh:"def"
abcdefgh:defexpr abcdefgh : "def"
0expr abcdefgh : ".*def"
6

That clears it up. Thankssorry about mixing up the $var and $line, I meant to write $var of course. Copy-pasted that line from the original code.
Thanks to both of you for helping me out.
-Anukta

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |