您的位置:首页 > 其它

grep语法

2015-09-14 16:52 155 查看

grep 根据模式搜索文本,并将符合模式的文本显示出来
Pattern 文本字符串和正则表达式的元字符组合而成匹配条件

grep [option] Pattern [file...]

1、查找带有root字符的行
grep 'root' /etc/passwd
2、查找带有root字符的行并高量显示
grep --color 'root' /etc/passwd
3、-v 方向查找,显示没有被匹配到的行
grep -v 'root' /etc/passwd
4、-o 只显示被匹配到的字符串
grep -o 'root' /etc/passwd
5、-A # 把匹配到的行后面的几行也显示
grep -A 2 '^core id' /proc/cpuinfo
6、-B # 把匹配到的行前面的几行也显示
grep -B 2 '^core id' /proc/cpuinfo
7、-C # 把匹配到的行前后面的各几行也显示
grep -C 2 '^core id' /proc/cpuinfo


*:任意长度的任意字符 >=0次
?:任意单个字符 0或1次
[]:指定范围内
[^]:指定范围外

正则表达式:REGular EXPression ,REGEXP
元字符
.:任意单个字符 grep --color 'r..t' /etc/passwd
[]:匹配指定范围内的任意单个字符
[^]:匹配指定范围外的任意单个字符
字符集合:
[:digit:]数字, [: 4000 lower:]小写字符,[:upper:]大写字符, [:punct:]标点符号
[:space:]空白字符,[:alpha:]所有字符,[:alnum:]所有数字和字符


字符匹配次数:
*:任意其前面的字符任意次
a , b , ab , aab, acb ,adb , amnb
a*b : b , ab , aab, acb ,adb , amnb --a可以出现或者不出现

.*:任意长度的任意字符
a.*b : ab , aab, acb ,adb , amnb
?:任意其前面的字符0或1次
a\?b : b , ab , aab, acb ,adb , amnb
\{m,n\}:匹配其前面的字符至少m次,至多n次
\{1,\} 至少一次,多了不限
\{0,3\} 最多3次,少了不限
grep 'a\{1,3\}b' grep1.txt
grep 'a.\{1,3\}b' grep1.txt

位置锚定:
^: 锚定行首,此字符后面的内容必须出现在行首
grep --color '^root' /etc/passwd
$: 锚定行尾,此字符前面的内容必须出现在行尾
grep --color 'w$' /etc/inittab
^$: 空白行

\<或\b:锚定词首,其后面的字符必须作为单词的首部出现
\>或\b:锚定词尾,其前面的字符必须作为单词的尾部出现

分组:
\(\)
\(ab\)* ab可以出现任意次
向后引用
\1:
\2:
\3:
例子:
He love his lover.
She like her liker.
He like his lover.
She love her liker.
She like him.

grep 'l..e' test.txt
grep 'l..e.*l..e' test.txt
grep '\(l..e\).*\1' test.txt

查找任意行中出现了一个数字,仍以该数字结尾的行
grep --color '\([0-9]\).*\1$' /etc/inittab
egrep --color '([0-9]).*\1$' /etc/inittab



扩展正则表达式grep -E egrep
分组()、{m,n}不需要加斜线
grep -E 'C|cat' test.txt
grep --color -E '(C|c)at' test.txt

至少一个空白字符开头的杭
grep --color -E '^[[:space:]]+' /etc/grub.conf
grep --color -E '^[[:space:]]{1}' /etc/grub.conf

找到1-255之间的整数 --()是关键
egrep --color '\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>' /etc/grub.conf

找出ifconfig结果中的ip地址,4个数字,每个数字都是0-255
ifconfig | egrep --color '\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>'
ifconfig | egrep --color '(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>





阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: