linux之基础正则表达式

正则表达式是为处理大量文本或者字符串而定义的一套规则,一般只有三剑客(grep、sed、awk) find ,开发语言 python,go支持,正则表达式分基本正则和扩展正则

避免的坑:所有的符号都是英文

说白了就是用几个符号替换一部分文本,例如有两行: hello java hello linux 这两行的共同点就是有hello,所以我们可以用 ^hello 或者 hello.* 来表示这两行,在这里 ^hello 或者 hello.* 就是正则表达式,正则表达式本身也是字符串,用一个字符串表示一堆字符串,这就是正则表达式的用处 很多人会问正则表达式和通配符有什么区别?如何区分通配符和正则表达式?

通配符和正则表达式区别

用途区别

通配符: 文件匹配 文件名匹配 *txt, *.log ,linux 大部分的命令都支持 正则表达式:三剑客(grep、sed、awk) find ,开发语言 python,go支持 等查找有规律的文本,如日志

正则表达式分类

本文对正则表达式的归纳主要从 正则表达式的 特殊字符入手,正则中的特殊字符有:

. * + ? ^ $ \ | / () {} [] 一共15 个字符,可以分类记忆为 (4 + 2 + 3 + 2 * 3):

4 个填充类标识: . * + ? 2 个锚点符号: ^ $ 3 个斜线: \ | / 6 个括号: ( ) { } [ ]

按照分类基础正则和扩展正则分类 基础正则 ^ $ ^$ . * .* \ [a,b,c] [a-z] 扩展正则 + | () {} ?

正则表达式

基本上从这两个方面就可以区分正则表达式和通配符,linux三剑客grep、sed、awk都是处理字符串的,经常会与正则表达式一起使用处理文本;除此之外的基本上都是关于目录或者文件名的,均是属于通配符。

- 基础正则表达式- 解释^^word word表示以word开头的内容$word$ 表示以word结尾的内容^$组合符,表示空行,这一行中没有任何内容.代表且只能代表任意一个字符\转义字符,将特殊字符取消特殊含义*匹配前一个字符(连续出现)0次或1次以上,重复0次代表空,即匹配所有内容.*组合符,匹配任意多个字符,任意,所有内内容^.*o组合符,以任意字符开头的所有内容^.*组合符,匹配任意多个字符开头的内容.*$组合符,匹配以任意多个字符结尾的内容[a,b,c]匹配abc其中的一个【^abc】匹配除了^ 后面的任意字符,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 -n 显示行号 cat -A 显示文件中隐藏的标记 如隐藏的结尾标志

[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

匹配配出日志中18:38.1十几 的日志

$ grep '18:38:1.' pcsc.sds-sds.debug.log

【5】过滤包含字符’'的行grep -n ‘\’ test.txt \表示将特殊字符转变回文本 \n 换行 \t 回车键

[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

【8】 连续出现4的匹配中 grep ‘4*’ pcsc.pcsc-web.debug.log

grep

grep 默认加上单引号, 默认给匹配中的字符他添加上颜色

alias egrep=‘egrep --color=auto’

$ alias grep='grep --color=auto'

alias egrep='egrep --color=auto'

grep -n 显示行号 grep -v 匹配结果取反,排除 grep -vn 取反显示行号

精彩内容

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: