简体   繁体   中英

wildcard in regular expression in shell script

I have a question regarding wildcard in shell script regular exression vi a.sh

if [[ $1 == 1*3 ]]; then
  echo "matching"
else
  echo "not matching"
fi

If I run sh a.sh 123 the output is: "matching".

But according to http://www.tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm :

* (asterisk)

the proceeding item is to be matched zero or more times. ie. n* will match n, nn, nnnn, nnnnnnn but not na or any other character.

it should match to only 3,13,113,111..3.

But why is it matching 123?

In the documentation you linked you are taking the part in which it talks about "Regular expressions".

However, what is important here is what is within "Standard Wildcards (globbing patterns)":

Standard Wildcards (globbing patterns)

this can represent any number of characters (including zero, in other words, zero or more characters). If you specified a "cd*" it would use "cda", "cdrom", "cdrecord" and anything that starts with “cd” also including “cd” itself. "m*l" could by mill, mull, ml, and anything that starts with an m and ends with an l.

That is, it does not refer to the previous character but to a set of characters (zero or more). It is what equivalent to a .* in normal regular expressions.

So the expression 1*3 matches anything starting with 1 + zero or more characters + 3 at the end.

There are two different pattern matching you find in the Unix/Linux World:

  • Regular Expressions : This is the complex pattern matching you find in grep , sed , and many other utilities. As time moved on, many extensions can be found. These extensions are referred to in POSIX as original (now considered obsolete), modern , and extended .
  • Globbing : This refers to the file matching you find when you do things such as *.txt to match all text files. These are much simpler and less extensive. There are a few extensions (like ** to match subdirectories in Ant).

When you use [[ ... == ... ]] without quotes in Bash, you are using globbing file matches. If you want to use regular expressions, you need to use the =~ operator:

if [[ $foo =~ ^11*3 ]]   # Matches 13, 113, 1113, 11113
then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM