良许Linux教程网 干货合集 grep中正则表达式使用方法

grep中正则表达式使用方法

grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

文字匹配

grep命令最基本的用法是搜索文件中的文字字符或字符序列。例如,要显示/etc/passwd文件中包含字符串“bash”的所有行,需要运行以下命令:

[root@localhost ~]# grep bash /etc/passwd
root:x:0:0:root:/root:/bin/bash
bob:x:1000:1001::/home/bob:/bin/bash
user01:x:1001:1002::/home/user01:/bin/bash
grep中的正则表达式grep中的正则表达式

默认情况下,grep命令是区分大小写的。这意味着大写和小写字符被视为不同的。要在搜索时忽略大小写,请使用-i选项。

如果搜索字符串包含空格,则需要用单引号或双引号将其括起:

[root@localhost ~]# grep "System message bus" /etc/passwd
dbus:x:81:81:System message bus:/:/sbin/nologin
grep中的正则表达式grep中的正则表达式

锚点

^符号匹配行首的空字符串。在下面的示例中,字符串“root”只有在行首出现时才匹配。

[root@localhost ~]# grep '^root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
grep中的正则表达式grep中的正则表达式

$要查找以字符串“bash”结尾的行,可以使用以下命令:

[root@localhost ~]# grep 'bash$' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bob:x:1000:1001::/home/bob:/bin/bash
user01:x:1001:1002::/home/user01:/bin/bash
grep中的正则表达式grep中的正则表达式

您还可以使用两个锚来构造正则表达式。例如,查看配置文件,不显示空行,请运行以下命令:

[root@localhost ~]# grep -v '^$' /etc/samba/smb.conf
grep中的正则表达式grep中的正则表达式

-v 反转匹配的意义,来选择不匹配的行。

|符号

| 是或者的意思。例如:想查看cpu是否支持虚拟化:

[root@localhost ~]# grep 'vmx\|svm' /proc/cpuinfo
flags  : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities
grep中的正则表达式grep中的正则表达式

如果使用扩展正则表达式,则不需要转义|,如下所示:

[root@localhost ~]# grep -E 'svm|vmx' /proc/cpuinfo
flags  : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities
grep中的正则表达式grep中的正则表达式

总结

正则表达式用于文本编辑器、编程语言和命令行工具,如grep、sed和awk。在搜索文本文件、编写脚本或过滤命令输出时,了解如何构造正则表达式非常有用。

以上就是良许教程网为各位朋友分享的Linu系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !

img
本文由 良许Linux教程网 发布,可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。
良许

作者: 良许

良许,世界500强企业Linux开发工程师,公众号【良许Linux】的作者,全网拥有超30W粉丝。个人标签:创业者,CSDN学院讲师,副业达人,流量玩家,摄影爱好者。
上一篇
下一篇

发表评论

联系我们

联系我们

公众号:良许Linux

在线咨询: QQ交谈

邮箱: yychuyu@163.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部