日期:2014-05-16  浏览次数:20623 次

Linux Shell常用技巧(二)

转自:http://www.cnblogs.com/stephen-liu74/archive/2011/11/14/2243694.html

?

七. grep家族:
?? ?
???1.? grep退出状态:
?? ?0: 表示成功;
?? ?1: 表示在所提供的文件无法找到匹配的pattern;
?? ?2: 表示参数中提供的文件不存在。
?? ?见如下示例:
?? ?/> grep 'root' /etc/passwd
?? ?root:x:0:0:root:/root:/bin/bash
?? ?operator:x:11:0:operator:/root:/sbin/nologin
?? ?/> echo $?
?? ?0
?? ?
?? ?/> grep 'root1' /etc/passwd? #用户root1并不存在
?? ?/> echo $?
?? ?1
?? ?
?? ?/> grep 'root' /etc/passwd1? #这里的/etc/passwd1文件并不存在
?? ?grep: /etc/passwd1: No such file or directory
?? ?/> echo $?
?? ?2
?? ?
???2.? grep中应用正则表达式的实例:
?? ?需要说明的是下面所涉及的正则表达式在上一篇中已经给出了详细的说明,因此在看下面例子的时候,可以与前一篇的正则说明部分结合着看。
?? ?/> cat testfile
??? northwest??????? NW????? Charles Main?????????? 3.0???? .98???? 3?????? 34
?? ?western?????????? WE?????? Sharon Gray????????? 5.3???? .97???? 5?????? 23
?? ?southwest?????? SW?????? Lewis Dalsass???????? 2.7???? .8?????? 2?????? 18
?? ?southern???????? SO?????? Suan Chin?????????????? 5.1???? .95???? 4?????? 15
?? ?southeast?????? SE??????? Patricia Hemenway??? 4.0???? .7?????? 4?????? 17
?? ?eastern?????????? EA??????? TB Savage??????????? ? 4.4???? .84???? 5?????? 20
?? ?northeast??????? NE??????? AM Main Jr.????????????? 5.1???? .94???? 3?????? 13
?? ?north????????????? NO?????? Margot Weber????????? 4.5???? .89???? 5?????? 9
?? ?central??????? ? ? CT??????? Ann Stephens????????? 5.7???? .94???? 5?????? 13

????
?? ?/> grep NW testfile???? #打印出testfile中所有包含NW的行。
?? ?northwest?????? NW????? Charles Main?? ??? ?3.0???? .98???? 3?????? 34
?? ?
?? ?/> grep '^n' testfile?? #打印出以n开头的行。
?? ?northwest?????? NW????? Charles Main?? ??? ?3.0???? .98???? 3?????? 34
?? ?northeast??????? NE?????? AM Main Jr.??? ??? ? 5.1???? .94???? 3?????? 13
?? ?north????????????? NO????? Margot Weber?? ?? 4.5???? .89???? 5?????? 9
?? ?
?? ?/> grep '4$' testfile?? #打印出以4结尾的行。
?? ?northwest?????? NW????? Charles Main?? ??? ?3.0???? .98???? 3?????? 34
?? ?
?? ?/> grep '5\..' testfile?#打印出第一个字符是5,后面跟着一个.字符,在后面是任意字符的行。
?? ?western???????? WE????? Sharon Gray??? ??? ?5.3???? .97???? 5?????? 23
?? ?southern??????? SO????? Suan Chin????? ??? ?? 5.1???? .95???? 4?????? 15
?? ?northeast?????? NE????? AM Main Jr.??? ??? ??? 5.1???? .94???? 3?????? 13
?? ?central?????????? CT????? Ann Stephens?? ??? ?5.7???? .94???? 5?????? 13
?? ?
?? ?/> grep '\.5' testfile? #打印出所有包含.5的行。
?? ?north?????????? NO????? Margot Weber?? ??? ?4.5???? .89???? 5?????? 9

?? ?/> grep '^[we]' testfile?#打印出所有以w或e开头的行。
?? ?western???????? WE????? Sharon Gray??? ??? ?5.3???? .97???? 5?????? 23
?? ?eastern????????? EA????? TB Savage????? ??? ? 4.4?