linux之基础正则表达式
正则表达式是为处理大量文本或者字符串而定义的一套规则,一般只有三剑客(grep、sed、awk)支持,正则表达式分基本正则和扩展正则
说白了就是用几个符号替换一部分文本,例如有两行:
hello java
hello linux
这两行的共同点就是有hello,所以我们可以用 ^hello 或者 hello.* 来表示这两行,在这里 ^hello 或者 hello.* 就是正则表达式,正则表达式本身也是字符串,用一个字符串表示一堆字符串,这就是正则表达式的用处
很多人会问正则表达式和通配符有什么区别?如何区分通配符和正则表达式?
区分通配符和正则表达式:
1.三剑客grep、sed、awk都是正则,其它都是通配符
2.文件目录名->通配符,文件内容/字符串->正则表达式
基本上从这两个方面就可以区分正则表达式和通配符,linux三剑客grep、sed、awk都是处理字符串的,经常会与正则表达式一起使用处理文本;除此之外的基本上都是关于目录或者文件名的,均是属于通配符。
| 基础正则表达式 | 解释 |
|---|---|
| ^ | ^word表示以word开头的内容 |
| $ | word$表示以word结尾的内容 |
| ^$ | 表示空行 |
| . | 代表且只能代表任意一个字符 |
| \ | 转义字符 |
| * | 重复之前的字符0或多次 |
| .* | 匹配任意多个字符 |
| [a,b,c] | 匹配abc其中的一个 |
| [a-z] | 匹配a-z其中的一个字符 |
测试文件
[root@linuxforliuhj test]# cat test.txt
hello this is linux
i am lhji
who are you
if you want me
张三是一个老师
李四是张三的媳妇
\HELLO
asssssdeforce
hey ZZZ
【1】过滤以i开头的行grep '^i' test.txt
[root@linuxforliuhj test]# grep '^i' test.txt
i am lhji
if you want me
【2】过滤以x结尾的行grep 'x$' test.txt
[root@linuxforliuhj test]# grep 'x$' test.txt
hello this is linux
【3】过滤空行grep -n '^$' test.txt
[root@linuxforliuhj test]# grep -n '^$' test.txt
3:
6:
【4】过滤每一行的第二个字符为e的行grep -n '^.e' test.txt
[root@linuxforliuhj test]# grep -n '^.e' test.txt
1:hello this is linux
11:hey ZZZ
【5】过滤包含字符’\'的行grep -n '\\' test.txt
[root@linuxforliuhj test]# grep -n '\' test.txt
grep: Trailing backslash
[root@linuxforliuhj test]# grep -n '\\' test.txt
9:\HELLO
【6】过滤包含小写字母a、b、c的行grep -n '[abc]' test.txt
[root@linuxforliuhj test]# grep -n '[abc]' test.txt
2:i am lhji
4:who are you
5:if you want me
10:asssssdeforce
【7】过滤包含大写字母的行grep -n '[A-Z]' test.txt
[root@linuxforliuhj test]# grep -n '[A-Z]' test.txt
9:\HELLO
11:hey ZZZ

236

被折叠的 条评论
为什么被折叠?



