曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4819|回复: 2
打印 上一主题 下一主题

grep 与正则表达式

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2008-12-14 23:00:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
沙发
 楼主| 发表于 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

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
板凳
 楼主| 发表于 2009-4-21 00:08:15 | 只看该作者

利用 grep 快速的在某目录下文件中查找某字符串

grep -r 要查找的字符串 目录
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-18 07:38 , Processed in 0.068038 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表