利用grep与正则表达式快速精确实现文本通配
什么是grep? grep (global search regular expression(RE) and print out the line,其全称意义为全局搜索正则表达式,并打印出来。是一种功能强大,简单易用的文本搜索工具。它能根据其后指定的匹配方式匹配出文件中的文本,并把匹配到的那整行都打印出来。 在Linux中grep家族有三个成员,分别是grep,egrep和fgrep,其使用方法略有不同,其中egrep是grep的扩展,而fgrep则是在进行文本通配时把所有的字母都当做单词来处理,让正则表达式中的元字符失去意义,当成普通单词来处理。在使用的时候可以用grep后接-E或者-F选项实现egrep和fgrep的功能。 grep的常用选项和一般用法。 grep的常常用选项有以下几个 -v:反向显示查找文本,即匹配到的反而不显示,显示未被匹配到的字符。 例:正常匹配文件test中的“hello“字符串 [root@grep tmp]# grep "hello" test hello 加-v选项 [root@grep tmp]# grep -v "hello" test this is a test txt welcome to use grep -i:文本匹配中忽略大小写 [root@grep tmp]# grep -i "HOW ARE YOU" test HOW ARE YOU how are you -n:在输出文本时显示其行号 [root@grep tmp]# grep -n "how are you" test 5:how are you -c:显示被匹配到的次数 [root@grep tmp]# grep -ic "how are you" test 2 --color=auto:用此选项显示被匹配到的字符串 [root@grep tmp]# grep --color=auto "how" test how are you 其他选项不再赘述,可通过查看grep帮助文档查看。 grep结合正则表达式实现快速准确匹配文本。 结合grep与正则表达式,能快速准确地找到所希望匹配到的字符串和行,加快工作效率。 例1:找出/etc/passwd文件中root所在的行 [root@grep tmp]# grep --color=auto "^root" /etc/passwd root:x:0:0:root:/root:/bin/bash 例2:找出/tec/passwd文件中的系统账号,显示其用户名和UID [root@grep tmp]# cut -d: -f1,3 /etc/passwd|grep --color=auto "&;[1-4[0-9][0-9]&;" uucp:10 operator:11 games:12 gopher:13 ftp:14 nobody:99 dbus:81 vcsa:69 haldaemon:68 gdm:42 ntp:38 apache:48 postfix:89 sshd:74 tcpdump:72 named:25 例3:取字符串/etc/sysconfig/的基名 [root@grep tmp]# echo /etc/sysconfig |grep -E -o "/[[:alpha:]]*$" | grep -o -E "[[:alnum:]]*" sysconfig 例4:匹配出testip文件中合理的ip地址 root@grep tmp]# cat testip 192168.0.1 192.155.234.2 256.234.245.654 123.234.212.12 1.0.0.1 [root@grep tmp]# cat testip |grep --colorauto -E "(^b[1-9]b|^b[1-9][0-9]b|^b1[0-9][0-9]b|^b2[1-3[0-9]).(b[0-9]b|b[1-9][0-9]b|b1[0-9][0-9]b|b2[0-4][0-9]b|b25[0-5]b).(b[0-9]b|b[1-9][0-9]b|b1[0-9][0-9]b|b2[0-4][0-9]b|b25[0-5]b).(b[0-9]b|b[1-9][0-9]b|b1[0-9][0-9]b|b2[0-4][0-9]b|b25[0-5]b)$" 192.155.234.2 123.234.212.12 1.0.0.1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |