Linux Shell教程(二) 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

grep与正规表示法——限定模式范围

我们可以利用 . 与 RE 字符及 来配置 0 个到无限多个重复字节, 那如果我想要限制一个范围区间内的重复字节数*呢?

范例1:找出两个到五个 o 的连续字串。

这时候就得要使用到限定范围的字符 {} 了。 但因为 { 与 } 的符号在 shell 是有特殊意义的,因此,我们必须要使用字符 \ 转义才行。 至于 {} 的语法是这样的,假设我要找到两个 o 的字串,可以是:

$ grep -n 'o\{2\}' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
9:Oh! The soup taste good.
18:google is the best tools for search ke
19:goooooogle yes!

范例2:找出 g 后面接 2 到 5 个 o ,然后再接一个 g 的字串。

$ grep -n 'go\{2,5\}g' regular_express.txt
18:google is the best tools for search keyword.

范例3:找出 2 个 o 以上的 goooo....g 。

$ grep -n 'go\{2,\}g' regular_express.txt
18:google is the best tools for search keyword.
19:goooooogle yes!
建立 regular_express.txt 文件后,按照范例运行命令,查看结果是否与教程一致。