04_04_linux_grep

本文介绍了如何使用grep命令进行文本查找,包括基本用法、选项参数及正则表达式的使用,帮助读者掌握高效的文本搜索技巧。

文本查找的需要(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.





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值