ITEEDU

4.3. Pattern匹配使用Bash特性

4.3.1. 字符范围

除了 grep 和正则表达式之外,shell里有很多无需使用外部程序就可以直接使用的匹配模板。

就和你已经知道的一样,*和?分别匹配任何字符串和任何单个字符,引用这些特殊字符来匹配他们的字面值:

cathy ~> touch "*"

cathy ~> ls "*"
*

你也可以使用方括号来匹配任何enclosed character or range of characters,如果一对字符被-分隔,一个例子But you can also use the square braces to match any enclosed character or range of characters, if pairs of characters are separated by a hyphen. An example:

cathy ~> ls -ld [a-cx-z]*
drwxr-xr-x    2 cathy	 cathy		4096 Jul 20  2002 app-defaults/
drwxrwxr-x    4 cathy    cathy          4096 May 25  2002 arabic/
drwxrwxr-x    2 cathy    cathy          4096 Mar  4 18:30 bin/
drwxr-xr-x    7 cathy    cathy          4096 Sep  2  2001 crossover/
drwxrwxr-x    3 cathy    cathy          4096 Mar 22  2002 xml/

列出了 cathy home目录里的所有以“a”,“a”,“b”,“c”,“x”,“y”开头的文件。

If the first character within the braces is “!” or “^”, any character not enclosed will be matched. To match the dash (“-”), include it as the first or last character in the set. The sorting depends on the current locale and of the value of the LC_COLLATE variable, if it is set. Mind that other locales might interpret “[a-cx-z]” as “[aBbCcXxYyZz]” if sorting is done in dictionary order. If you want to be sure to have the traditional interpretation of ranges, force this behavior by setting LC_COLLATE or LC_ALL to “C”.

4.3.2. 字符族

字符族可以用方括号来指定,使用语法 [:CLASS:],CALSS是定义在POSIX标准中的取以下某个值

alnum”, “alpha”, “ascii”, “blank”, “cntrl”, “digit”, “graph”, “lower”, “print”, “punct”, “space”, “upper”, “word” or “xdigit”.

一些例子:

cathy ~> ls -ld [[:digit:]]*
drwxrwxr-x    2 cathy	cathy		4096 Apr 20 13:45 2/

cathy ~> ls -ld [[:upper:]]*
drwxrwxr--    3 cathy   cathy           4096 Sep 30  2001 Nautilus/
drwxrwxr-x    4 cathy   cathy           4096 Jul 11  2002 OpenOffice.org1.0/
-rw-rw-r--    1 cathy   cathy         997376 Apr 18 15:39 Schedule.sdc

当开启 extglob shell选项(使用 shopt 内建命令), several extended pattern matching operators are recognized. Read more in the Bash info pages, section Basic shell featuresShell ExpansionsFilename ExpansionPattern Matching.