Linux Shell教程(二) 互动版

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

grep与正规表示法——行首与行尾

在正规表示法中,行首与行尾字节分别用 ^ 和 $ 表示。

范例1:让 the 只在行首时列出。

$ grep -n '^the' regular_express.txt
12:the symbol '*' is represented as start.

此时,就只剩下第 12 行,因为只有第 12 行的行首是 the 开头啊!

范例2:查找开头是小写字节的行。

$ grep -n '^[a-z]' regular_express.txt
2:apple is my favorite food.
4:this dress doesn't fit me.
10:motorcycle is cheap than car.
12:the symbol '*' is represented as start.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let's go.

范例3:查找开头不是英文字母的行。

$ grep -n '^[^a-zA-Z]' regular_express.txt 1:"Open Source" is a good mechanism to develop programs. 21:# I am VBird


*注意*:*^ 符号*,在字符类符号(括号[])之内与之外是不同的! *在 [] 内代表『反向选择』,在 [] 之外则代表定位在行首的意义*!

***范例4***:找出行尾结束为小数点 (.) 的那一行呢。

$ grep -n '.$' 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. 4:this dress doesn't fit me. 10:motorcycle is cheap than car. 11:This window is clear. 12:the symbol '*' is represented as start. 15:You are the best is mean you are the no. 1. 16:The world is the same with "glad". 17:I like dog. 18:google is the best tools for search keyword. 20:go! go! Let's go.


*注意*:因为小数点具有其他意义(底下会介绍),所以必须要使用*转义字符(\)来解除其特殊意义*!

***范例5***:找出所有空白行。

$ grep -n '^$' regular_express.txt 22: ```

因为只有行首跟行尾 (^$),所以,这样就可以找出空白行啦!

建立 regular_express.txt 文件后,按照范例运行命令,查看结果是否与教程一致。