@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