菜鸟笔记
提升您的技术认知

grep中的正则表达式-ag真人游戏

正则表达式是匹配一组字符串的模式。模式由操作符、构造文字字符和具有特殊意义的元字符组成。grep支持三种正则表达式语法:basic、extended和perl兼容。

如果没有提供正则表达式类型,grep将搜索模式解释为基本的正则表达式。要将模式解释为扩展的正则表达式,请使用-e。

文字匹配

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命令是区分大小写的。这意味着大写和小写字符被视为不同的。要在搜索时忽略大小写,请使用-i选项。

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

[root@localhost ~]# grep "system message bus" /etc/passwd
dbus:x:81:81:system message bus:/:/sbin/nologin

锚点

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

[root@localhost ~]# grep '^root' /etc/passwd
root:x:0:0:root:/root:/bin/bash


$要查找以字符串“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


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

[root@localhost ~]# grep -v '^$' /etc/samba/smb.conf


-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


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

[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、sed和awk。在搜索文本文件、编写脚本或过滤命令输出时,了解如何构造正则表达式非常有用。

网站地图