@OP,
Is glob pettern not only used for file names?
沒有, 「水珠」 模式不僅可用於文件名。你也可以使用它來比較字符串。在你的例子中,你可以使用case/esac來查找字符串模式。
gg=svm-grid-ch
# looking for the word "grid" in the string $gg
case "$gg" in
*grid*) echo "found";;
esac
# [[ $gg =~ ^....grid* ]]
case "$gg" in ????grid*) echo "found";; esac
# [[ $gg =~ s...grid* ]]
case "$gg" in s???grid*) echo "found";; esac
In bash, when to use glob pattern and when to use regular expression? Thanks!
正則表達式更靈活,比「glob模式」,「方便」,但除非你正在做的複雜任務「通配符/擴展通配」不能輕易提供,那麼就沒有需要使用正則表達式。 正則表達式不支持版本的bash < 3.2(如丹尼斯提到的),但仍可以使用擴展匹配(通過設置extglob
)。有關擴展匹配,請參閱here和一些簡單示例here。
更新OP:實施例發現,用2個字符(的點裝置1個字符「」),接着的‘g’開頭的文件使用正則表達式
例如輸出
$ shopt -s dotglob
$ ls -1 *
abg
degree
..g
$ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
abg
degree
..g
在上述,這些文件是匹配的,因爲它們的名稱包含2個字符,後面跟着「g」。 (即..g
)。
用通配符會是這樣的等價的:(看reference爲?
意義和*
)
$ for file in ??g*; do echo $file; done
abg
degree
..g
所以字符串匹配有兩種方法:glob模式和正則表達式? glob pettern不僅用於文件名嗎?在bash中,何時使用glob模式以及何時使用正則表達式?謝謝! – Tim 2010-02-27 20:24:12
@Tim:Globbing可用於大多數或所有版本的Bash。正則表達式匹配僅適用於版本3和更高版本,但我建議僅在3.2及更高版本中使用它。正則表達式比globbing更**更多。 – 2010-02-27 22:30:36