Grep(Regex)中的正则表达式

2023-11-28 0 808

在Linux系统中grep时最常用的处理文件的的工具之一,grep命令最基本的用法是搜索文件中的文字字符或字符序列

文字匹配

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都可以用于文本编辑,编辑语言,了解了正则表达式之后再搜索文本,编写脚本或过滤命令输出非常有用。

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

本文来源:www.lxlinux.net/530.html,若引用不当,请联系修改。

相关文章

猜你喜欢
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

  • 0 +

    访问总数

  • 0 +

    会员总数

  • 0 +

    文章总数

  • 0 +

    今日发布

  • 0 +

    本周发布

  • 4975 +

    运行天数

你的前景,远超我们想象