|
沙发

楼主 |
发表于 2008-12-15 00:08:00
|
只看该作者
正则表达式在 grep 中的应用
假设 new 文件的内容如下:
root
hello-root
root,fuck
^root
binroot
rootnew
Root
Root123
ROOT
|
1、找出文件中的空行并打印出空行的行号beyes@linux-beyes:~/桌面> grep -n ^$ new
5:
6: 注:^ 表示从一行的开始匹配
$ 表示匹配到一行的结束
上面,从开始到结束的匹配并没有给出内容,故为找出空行一意。
或者:beyes@linux-beyes:~/桌面> grep -n -v . new
5:
6: 注:-v 为过滤;而 . 表示匹配任意一个字符。综合起来就是,过滤掉任意一个字符(为空),即为空行。
假设文件 new 含有如下的内容:
hello man,is abc ok?
hehe,no,def is ok!
abcdef ready?
abc def can be ok.
none
null
no ABC or DEF
no abc or def
|
1、输出包含 abc 或 def 或 同时包含两者的行beyes@linux-beyes:~/桌面> grep -F 'abc // F 参数表示用用新行分隔需要匹配的字符串,只要满足其中之一即可
def' new
hello man,is abc ok?
hehe,no,def is ok!
abcdef ready?
abc def can be ok.
no abc or def
或者:beyes@linux-beyes:~/桌面> grep -E 'abc|def' new
hello man,is abc ok?
hehe,no,def is ok!
abcdef ready?
abc def can be ok.
no abc or def
假设一个文本内容如下:
abc display
display abc
no abc display
def display
display def
no def display
abc
def
abcdef
|
那么下面两个命令要求精确显示仅包含 abc 或者 def 的行并打印出行号:beyes@linux-beyes:~/桌面> grep -E -n '^abc$|^def$' new
7:abc
8:def
或者:
beyes@linux-beyes:~/桌面> grep -F -x -n 'abc //参数 -x 表示只能选择完整匹配一行的匹配
def' new
7:abc
8:def |
|