日期:2014-05-16  浏览次数:20605 次

【每天一个Linux命令】17. 强大的文件搜索工具grep&&正则表达式

#新建一个测试文件,下面会用到

bixiaopeng@bixiaopengtekiMacBook-Pro ~$ cat testgrep
wirelessqa is my blog
wirelestqa is testfile
wirelesmqa is testfile
mmmqa is testfile
mmqa
mqa is testfile
Wirelessqa is my blog
my blog is wirelessqa
my name is bixiaopeng
bixiaopeng is my name
bxp is my name
my name is bxp
my name is (bxp)
b$##

1. 匹配行的开始 ^  


#例:'^wirelessqa'匹配所有以wirelessqa开头的行
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e ^wirelessqa testgrep
wirelessqa is my blog
#或
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e ^[wirelessqa] testgrep
wirelessqa is my blog

2. 匹配定行的结束 $ 

#例:'wirelessqa$'匹配所有以wirelessqa结尾的行
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e wirelessqa$ testgrep
my blog is wirelessqa

3. 匹配一个非换行符的字符 

#例:'wireles.qa'匹配wireles后接一个任意字符,然后是qa
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e wireles.qa testgrep
wirelessqa is my blog
wirelestqa is testfile
wirelesmqa is testfile
my blog is wirelessqa

4. 匹配零个或多个先前字符  

#例1:' *qa'匹配所有一个或多个空格后紧跟qa的行
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e m*qa testgrep
wirelessqa is my blog
wirelestqa is testfile
wirelesmqa is testfile
mmmqa is testfile
mqa is testfile
Wirelessqa is my blog
my blog is wirelessqa
#例2: .*一起用代表任意字符
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e .*qa testgrep
wirelessqa is my blog
wirelestqa is testfile
wirelesmqa is testfile
mmmqa is testfile
mqa is testfile
Wirelessqa is my blog
my blog is wirelessqa

5. 匹配一个指定范围内的字符[]

#例1: '[Ww]irelessqa'匹配Wirelessqa和wirelessqa
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e [Ww]irelessqa testgrep
wirelessqa is my blog
Wirelessqa is my blog
my blog is wirelessqa

#例子2:[m*qa]匹配以m开头的字符或以qa结尾包含一个或多个m的字符
bixiaopeng@bixiaopengtekiMacBook-Pro ~$ grep -e [m*qa] testgrep
wirelessqa is my blog
wirelestqa is testfile
wirelesmqa is testfile
mmmqa is testfile
mqa is testfile
Wirelessqa is my blog
my blog is wirelessqa
my name is bixiaopeng
bixiaopeng is my name
bxp is my name
my name is bxp

6. 匹配一个不在指定范围内的字符[^]  

#例:'[^a-fh-m]qa'匹配不包含a-f和h-m的一个字母开头,紧跟qa的行