曲径通幽论坛

标题: grep 与正则表达式 [打印本页]

作者: beyes    时间: 2008-12-14 23:00
标题: grep 与正则表达式
grep应用举例

1、把 /etc/passwd 里面包含 root字符串的行显示出来:
beyes@linux-beyes:~/桌面> grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash

2、显示包含欲搜索字符串的行的行号:
beyes@linux-beyes:~/桌面> grep -n root /etc/passwd
34:root:x:0:0:root:/root:/bin/bash


假设有一下的一个名为 new-1 的文本,内容为:

hello world,hehe,are you ok?
hello world,are you ok,hehe?
world is round.

1、输出不含有 hehe 字符串的行以及行号:
beyes@linux-beyes:~/桌面> grep -v -n hehe new-1                      //-v 参数是进行过滤
1:
4:world is round.

2、忽略大小写输出:
假设 new 文件的内容为
root
hello-root
    root,fuck
^root

binroot
rootnew
Root
Root123
ROOT

beyes@linux-beyes:~/桌面> grep root new
root
hello-root
    root,fuck
^root
binroot
rootnew
beyes@linux-beyes:~/桌面> grep -i ROOT new
root
hello-root
    root,fuck
^root
binroot
rootnew
Root
Root123
ROOT

作者: beyes    时间: 2008-12-15 00:08
标题: 正则表达式在 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

作者: beyes    时间: 2009-4-21 00:08
标题: 利用 grep 快速的在某目录下文件中查找某字符串
grep -r 要查找的字符串 目录




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2