linux基本命令之grep

概念

其功能是从文本文件或管道数据流中筛选匹配的行及数据,如果再配和正则表达式的技术一起使用,则功能更加强大

语法格式:

 选项说明:

正则匹配的主要参数:

\: 忽略正则表达式中特殊字符的原有含义。
^:匹配正则表达式的开始行。
$: 匹配正则表达式的结束行。
\<:从匹配正则表达 式的行开始。
\>:到匹配正则表达式的行结束。
[ ]:单个字符,如[A]即A符合要求 。
[ - ]:范围,如[A-Z],即A、B、C一直到Z都符合要求 。
.:所有的单个字符。
*:所有字符,长度可以为0。

 案例1:使用grep过滤不包含hello的行

/home/user # cat hello.txt                                                                                 
hello world                                                                     
i am student                                                                    
welcome come to china        
                                                   
/home/user # grep -v "hello" hello.txt                                                                                                                                                                                               
i am student                                                                    
welcome come to china                                                                                                                    

案例2:grep命令显示过滤后的内容的行号

/home/user # grep -n "hello" hello.txt                                          
3:hello world  

案例3:利用grep搜索符合要求的用户(查到有r的用户名)

/home/user # grep r ../../etc/passwd                                            
root::0:0::/root:/bin/sh                                                        
sshd:*:27:27:sshd privsep:/var/empty:/sbin/nologin                              
user:CJDfUrYuMxw9.:1000:1000:Linux User,,,:/home/user:/bin/sh 

案例4:配合正则使用,显示所有包含搜索字符串满足i到s的行。

~ $ cat hello.txt                                                               
i am student                                                                    
i am china                                                                      
hello                                                                           
is                                                                              
~ $ grep '[i-s]' hello.txt                                                      
i am student                                                                    
i am china                                                                      
hello                                                                           
is    

 

posted @ 2020-06-18 13:04  步入飞花  阅读(273)  评论(0编辑  收藏  举报