17、grep(Global Regular Expression Print)常用参数

1、Usage: grep [OPTION]... 'PATTERN' [FILE]...

Search for PATTERN in each FILE or standard input.

PATTERN is, by default, a basic regular expression (BRE).

Example: grep -i 'hello world' menu.h main.c

2、常用参数【option

1)-E--extended-regexp

采用扩展表示式去解释样式。

-i, --ignore-case        ignore case distinctions

-v, --invert-match        select non-matching lines

ps -ef | grep '^td*' | grep -v 'grep' | wc -l //-v 'grep'的排除项可以多个,用|连接

ps -aux

2)-c :打印匹配的行数

-n:打印包含匹配项的行和行标

-l:查询多文件时只输出包含匹配字符的文件名。

-r:递归查询子目录

-q,-quiet:取消显示,只返回退出状态。0表示找到了匹配的行。

-?:显示匹配行上下?行,如:grep -2 pattern filnam 显示匹配行的上下2行(为-C选项)

-s,–silent:不显示关于不存在或者无法读取文件的错误信息

-w,--word-regexp,匹配整个单词,cat test | grep -w zhan

-x:匹配整行。

-H, --with-filename:当搜索多个文件时,显示匹配文件名前缀

-o Print only the matched (non-empty) parts of a matching line, with each such part on 

a separate output line.

grep -l pattern files :只列出匹配的文件名。

grep -L pattern files :列出不匹配的文件名。

grep -w pattern files :只匹配整个单词,而不是字符串的一部分(如匹配'magic',而不是'magical')

grep pattern1 | pattern2 files //或关系

grep pattern1 files | grep pattern2 //相当于与关系

3、pattern

正则表达式

4、示例

grep -c '^$' test.txt  //查找空行的行数

grep 'test' d*  //显示所有以d开头的文件中包含test的行。

grep 'test' aa bb cc //显示在aabbcc文件中匹配test的行。

grep '[a-z]\{5\}' aa //显示所有包含每个字符串至少有5个连续小写字符的字符串的行。

grep '\<man' me.txt //要求词首是man

grep '\<man\>' me.txt //只匹配man

grep -rin me.txt `ls | grep -vE 'bin|boot|dev|initrd|lib'` //

cat test |grep '^\(root\|zhang\)' //匹配首单词是rootzhang的行

5、复杂一点

$ grep 'w\(es\)t.*\1' aa

    如果west被匹配,则es就被存储到内存中,并标记为1,然后搜索任意个字符(.*),这些字符后面紧跟着另外一个es(\1),找到就显示该行。如果用egrepgrep -E,就不用”\”号进行转义,直接写成’w(es)t.*\1′就可以了。

默认情况下,'grep'只搜索当前目录;如果此目录下有许多子目录,用:

明确要求搜索子目录:grep -r

或忽略子目录:grep -d skip

来进行。

6、[split] 分割文件 [paste] 以行连接文件 [join] 以字段连接文件 [grep] 查询文字 [uniq] 过滤重复部分显示文件内容 [tr] 替换文字 [sed] 替换文字

7、我们发现,grep的很多选项的字母大小写具有相反的含义,如-H表示搜索多文件时列出匹配行前的文件名,而-h则不列出;

参考

1】 详解

http://blog.csdn.net/greytree/article/details/428532

2man手册

3http://blog.sina.com.cn/s/blog_4af3f0d20100etjv.html

4http://www.9usb.net/200902/linux-grep.html

5http://www.cppblog.com/jb8164/archive/2007/12/21/39187.html

6http://blog.microsuncn.com/?p=1239

7】对grep的常用命令进行了翻译,并给出了详细的例子:

http://blog.51yip.com/linux/1008.html

原文地址:https://www.cnblogs.com/mydomain/p/2155338.html