grep 是一个命令行最初用于 Unix 操作系统的工具。在给出文件列表或标准输入后,grep 会对匹配一个或多个正则表达式的文本进行搜索,并只输出匹配的文本。 功能和用法
这个命令搜索整个文件中匹配给定正则表达式的文本行,并显示出来。有很多不同的命令行用于改变grep的默认行为,包括显示出不匹配的文本行、查找或排除搜索的文件以及用不同的方式在输出中进行注释。同时也有很多经典Unix下grep的现代版本,这些版本都有着独特的功能。 这里是一个常见的grep用法:
在这个例子里,grep会返回“fruitlist.txt”中所有包含“apple”的文本行。要注意的是,grep不会返回匹配“Apple” (A字母大写)的文本行,因为grep默认情况下是大小写敏感的。像大多数Unix命令行一样,grep接受参数来改变或增加一些特别的功能。例如:
这个命令会返回所有匹配“apple”、“Apple”、“apPLE”或其它混合大小写的拼写。 在一些grep版本中,参数 -e 可以用于使用多个匹配样式来进行搜索。 UsageThis 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 点击进入 Grep 项目主页 |