设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客

正则搜索工具:grep 2.7 发布

2010-9-21 18:05| 发布者: walkerxk| 查看: 3838| 评论: 0|来自: OSMSG

摘要: grep 是一个命令行最初用于 Unix 操作系统的工具。在给出文件列表或标准输入后,grep 会对匹配一个或多个正则表达式的文本进行搜索,并只输出匹配的文本。功能和用法这个程序的名称来自Unix文本编辑器ed类似操作的命 ...

grep 是一个命令行最初用于 Unix 操作系统的工具。在给出文件列表或标准输入后,grep 会对匹配一个或多个正则表达式的文本进行搜索,并只输出匹配的文本。

功能和用法

这个程序的名称来自Unix文本编辑器ed类似操作的命令:

g/re/p

这个命令搜索整个文件中匹配给定正则表达式的文本行,并显示出来。有很多不同的命令行用于改变grep的默认行为,包括显示出不匹配的文本行、查找或排除搜索的文件以及用不同的方式在输出中进行注释。同时也有很多经典Unix下grep的现代版本,这些版本都有着独特的功能。

这里是一个常见的grep用法:

grep apple fruitlist.txt

在这个例子里,grep会返回“fruitlist.txt”中所有包含“apple”的文本行。要注意的是,grep不会返回匹配“Apple” (A字母大写)的文本行,因为grep默认情况下是大小写敏感的。像大多数Unix命令行一样,grep接受参数来改变或增加一些特别的功能。例如:

grep -i apple fruitlist.txt

这个命令会返回所有匹配“apple”、“Apple”、“apPLE”或其它混合大小写的拼写。

在一些grep版本中,参数 -e 可以用于使用多个匹配样式来进行搜索。

Usage

This is an example of a common grep usage:

grep apple fruitlist.txt

In this case, grep prints all lines containing apple from the file fruitlist.txt, regardless of word boundaries; therefore lines containing pineapple or apples are also printed. The grep command is case sensitive by default, so this example’s output does not include lines containing Apple (with a capital A) unless they also contain apple.

Regular expressions can be used to match more complicated queries. The following prints all lines in the file that begin with the letter a, followed by any one character, then the letters ple.

grep ^a.ple fruitlist.txt

As noted above, the term “grep” derives from a usage in ed and related text editors. Before grep existed as a separate command, the same effect might have been achieved by doing:

ed fruitlist.txtg/^a.ple/pq

where the second line is the command given to ed to print the relevant lines, and the third line is the command to exit from ed.

Like most Unix commands, grep accepts options in the form of command-line arguments, to change many of its behaviors. For example:

grep -i apple fruitlist.txt

This prints all lines containing apple regardless of capitalization. The -i argument tells grep to be case insensitive, or to ignore case.

To print all lines containing apple as a word (pineapple and apples will not match):

grep -w apple fruitlist.txt

But if fruitlist.txt contains apple word followed by hyphen (-) character, it will also get matched.

cat fruitlist.txtappleapplespineappleapple-apple-fruitfruit-applegrep -w apple fruitlist.txtappleapple-apple-fruitfruit-apple

点击下载grep2.7

点击进入 Grep 项目主页


酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部