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

Time:03-06

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

CodePudding user response:

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*

CodePudding user response:

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

#!/bin/sh

teststring="abcdx.rubbish,y"

while read 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.

  • Related