您的位置:首页 > 运维架构 > Linux

04_04_linux_grep

2016-11-13 21:23 232 查看
文本查找的需要(grep、egrep、fgrep)

模式pattern,文本字符和正则表达式的元字符组合而成匹配条件

grep:根据模式,搜索文本,并将符合模式的文本显示出来

 grep [OPTIONS] PATTERN [FILE...]

[root@localhost /]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
-i:忽略大小写

--color:颜色标出

-v:反向查找

-o:只显示被匹配的串

[root@localhost /]# grep -o 'root' /etc/passwd
root
root
root
root


正则表达式:regular expression、REGEXP
元字符:

.:任意单个字符

[root@localhost /]# grep -o 'r..t' /etc/passwd
root
root
root
root
r/ft


匹配次数:
*:匹配其前面的字符任意次

例子:a*b  匹配b任意次

[root@localhost /]# grep 'a*b' /tmp/greptest
b
ab
aab
acb
anmnb
.*:a.*b  a和b间任意字符

[root@localhost /]# grep 'a.*b' /tmp/greptest
ab
aab
acb
anmnb


\?:匹配前面字符1次或0次
[root@localhost /]# grep --color 'a\?b' /tmp/greptest
b
ab
aab
acb
anmnb
[root@localhost /]# grep --color 'a\?' /tmp/greptest
a
b
ab
aab
acb
anmnb


\{m,n\}:匹配其前面的字符至少m次,至多n次

位置锚定

^:锚定行首,出现在前面

[root@localhost /]# grep  '^r..t' /etc/passwd
root:x:0:0:root:/root:/bin/bash
$:锚定行尾,出现在后面
[root@localhost /]# grep --color 'b$' /tmp/greptest
b
ab
aab
acb
anmnb
[root@localhost /]# grep --color 'a$' /tmp/greptest
a

^$ :空白行

[root@bogon ~]# grep '^$' /etc/passwd | wc -l
8
[]:匹配指定范围内的任意单个字符

[^]:匹配指定范围外的任意单个字符

字符集合:[:digit:] [:lower:][:upper:][:alnum:][:punct:][:space:]
\<或\b:其后面的任意字符必须作为单词首部出现

[root@bogon ~]# grep "\<root" test4.txt
this is root.
the user is root.
rooter is dog's name


\>或\b:其前面的任意字符必须作为单词尾部出现

[root@bogon ~]# grep "root\>" test4.txt
this is root.
the user is root.
chroot is a command.


[root@bogon ~]# grep "\<root\>" test4.txt
this is root.
the user is root.


分组:
\(\)

\(ab\)*:后向应用ab可以出现任意次

\1:引用第一个左括号出现的词组一次

[root@bogon /]# grep 'l..e.*l..e' test/txt
he love his lover.
she like his lover.
he like his liker.
she love her liker.
[root@bogon /]# grep '\(l..e\).*\1' test/txt
he love his lover.
he like his liker.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux shell