标签:grep正则表达式
grep(Global search REgular expression and Print out the line)是一种以行为单位按照给定的pattern(模式)进行文本搜索文本处理器。
在使用的时候,我们通常有这种感觉,每个选项我都差不多记住了,但是一到用的时候就想不来,请以我的方式一起来学习如何使用grep正则表达式。
首先科普一下选项:
常用选项:
--color=auto:对匹配到的文本着色后高亮显示;
-i:忽略字符大小写;
-o:仅显示匹配 到的文本自身;
-v, --invert-match:反向匹配;
-E:支持扩展的正则表达式;
-q, --quiet, --silient:静默模式,不输出任何信息;
pattern:
*:匹配前面的字符任意次(0,1或多次);
.*:任意长度的任意字符;
\+:匹配前面的字符至少1次;
\?:匹配前面的0次或1次,即前面的字符可有可无;
\{m\}:其前面的字符出现m次,m为非负整数;
\{m,n\}:其前面的字符出现m次,m为非负整数;[m,n];
^:行首锚定;用于模式的最左侧,^PATTERN;
$:行尾锚定;用于模式的最右侧,PATTERN$;
\<或\b:词首锚定,用于单词模式的左侧;
\>或\b:词尾锚定,用于单词模式的右侧;
一定要理解:grip使部分匹配,以行为单位进行处理的;
让我们以使用者的角度来学习一下正则表达式。文本搜索,无非是查找。我先自己编辑了一个文件。这是一偶的一点介绍。
①先看看他是否喜欢John;
(这个应该没有什么好说的,直接查找他就是了)
[root@localhost tmp]# grep "Michael Jordan" test.txt
I like my liker that he is the Michael Jordan.
②规定一行一句话,行首有小写字母应该有错;
(定位行首就用^,小写字母用[a-z][[:lower:]]等加一起就可以了)
[root@localhost tmp]# grep "^[a-z].*" test.txt
you may ask me how many? is 1 is 2 is 34567 is 999
that is not true.
③看看他的like和love情况吧;
(要找同一个单词出现两次,就想有grep有一个特征:可以用‘\(’,‘\)‘来保存匹配到的部分,这部分是保存在\1中的,这个是一个整体匹配,也就是grep在查找\1时,必须与前面一模一样)
[root@localhost tmp]# grep "\(l..e\).*\1" test.txt
I like my liker that he is the Michael Jordan.
I love my lover that he is Michael Jackson.
Where I AM IN the university,I have lover,but she don‘t love me.
[root@localhost tmp]# grep "\(l..e\).*\1" test.txt
I like my liker that he is the Michael Jordan.
I love my lover that he is Michael Jackson.
Where I AM IN the university,I have lover,but she don‘t love me.
③好像没有哪个单词有三个连续相同的字母;
[root@localhost tmp]# grep "\(.\)\1\1" test.txt
Where I AM IN the university,I have lover,but she don‘t lllove me.
you may ask me how many? is 1 is 2 is 34567 is 999
④看看他是不是很自我;
(定位行首用^)
[root@localhost tmp]# grep "^I" test.txt
I like playing basketball .
I am very simplicity.
I like my liker that he is the Michael Jordan.
I love my lover that he is Michael Jackson.
It was long and long ago.
I am still a boy.
I have no girlfriend,and that made me crazy.But i am truly believe that a beautiful girl will comes one day.
I know that is a little long from now.
⑤一个思路供大家参考
本文出自 “Linux” 博客,请务必保留此出处http://ridingonhorse.blog.51cto.com/11265295/1748888
标签:grep正则表达式
原文地址:http://ridingonhorse.blog.51cto.com/11265295/1748888