Linux Shell教程(二) 互动版

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

grep与正规表示法——任意字节与重复字节

任意一个字节 . 与重复字节 * 这两个符号在正规表示法的意义如下:

  • . (小数点):代表“一定有一个任意字节”的意思;
  • *(星号):代表“重复前一个字符, 0 到无穷多次”的意思,为组合形态

范例1:找出 g??d 的字串,亦即共有四个字节,起头是 g 而结束是 d 。

$ grep -n 'g..d' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
9:Oh! The soup taste good.
16:The world <Happy> is the same with "glad".

因为强调 g 与 d 之间一定要存在两个字节,因此,第 13 行的 god 与第 14 行的 gd 就不会被列出来啦!

范例2:列出有 oo, ooo, oooo 等等的数据, 也就是说,至少要有两个(含) o 以上。

分析:因为 代表的是 "重复 0 个或多个前面的 RE 字符" 的意义, 因此, "o" 代表的是:"拥有空字节或一个 o 以上的字节",因此,"grep -n 'o*' regular_express.txt"将会把所有的数据都列印出来终端上!

当我们需要“至少两个 o 以上的字串”时,就需要 ooo* ,亦即是:

$ grep -n 'ooo*' 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 keyword.
19:goooooogle yes!

范例3:找出这样的字串,开头与结尾都是 g,但是两个 g 之间仅能存在至少一个 o ,亦即是 gog, goog, gooog.... 等等。

$ grep -n 'goo*g' regular_express.txt
18:google is the best tools for search keyword.
19:goooooogle yes!

范例4:找出 g 开头与 g 结尾的行,当中的字符可有可无。

$ grep -n 'g.*g' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
14:The gd software is a library for drafting programs.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let's go.

因为是代表 g 开头与 g 结尾,中间任意字节均可接受,所以,第 1, 14, 20 行是可接受的喔! 这个 .* 的 RE 表示任意字符是很常见的.

范例5:找出 "任意数字" 的行。

因为仅有数字,所以就成为:

$ grep -n '[0-9][0-9]*' regular_express.txt
5:However, this dress is about $ 3183 dollars.
15:You are the best is mean you are the no. 1.
建立 regular_express.txt 文件后,按照范例运行命令,查看结果是否与教程一致。