Peter McN
Peter McN

Reputation: 31

In Bash, is it possible to match a string variable containing wildcards to another string

I am trying to compare strings against a list of other strings read from a file.

However some of the strings in the file contain wildcard characters (both ? and *) which need to be taken into account when matching.

I am probably missing something but I am unable to see how to do it

Eg.

I have strings from file in an array which could be anything alphanumeric (and include commas and full stops) with wildcards : (a?cd, xy, q?hz, j,h-??)

and I have another string I wish to compare with each item in the list in turn. Any of the strings may contain spaces.

so what I want is something like

teststring="abcdx.rubb ish,y"

matchstrings=("a?cd" "*x*y" "q?h*z" "j*,h-??")

for i in "${matchstrings[@]}" ; do

    if [[ "$i" == "$teststring" ]]; then # this test here is the problem
        <do something>
    else
        <do something else>
    fi
done

This should match on the second "matchstring" but not any others

Any help appreciated

Upvotes: 3

Views: 1302

Answers (2)

Jens
Jens

Reputation: 72657

You can do this even completely within POSIX, since case alternatives undergo parameter substitution:

#!/bin/sh

teststring="abcdx.rubbish,y"

while IFS= read -r matchstring; do
  case $teststring in
  ($matchstring) echo "$matchstring";;
  esac
done << "EOF"
a?cd
*x*y
q?h*z
j*,h-??
EOF

This outputs only *x*y as desired.

Upvotes: 3

chepner
chepner

Reputation: 531255

Yes; you just have the two operands to == reversed; the glob goes on the right (and must not be quoted):

if [[ $teststring == $i ]]; then

Example:

$ i=f*
$ [[ foo == $i ]] && echo pattern match
pattern match

If you quote the parameter expansion, the operation is treated as a literal string comparison, not a pattern match.

$ [[ foo == "$i" ]] || echo "foo != f*"
foo != f*

Spaces in the pattern are not a problem:

$ i="foo    b*"
$ [[ "foo    bar" == $i ]] && echo pattern match
pattern match

Upvotes: 5

Related Questions