Grep与正则表达式
其实学过正则表达式之后这些就不算啥事儿了,建议先学一下正则然后再来看.
不过直接看下面的更功利一些,毕竟看完了就可以直接用了.
下面这个是测试文的内容:
➤ cat -n fortune
1 All generalizations are false, including this one.
2 -- Mark Twain
3 Many pages make a thick book, except for pocket Bibles which are on very
4 very thin paper.
5
6 Remark of Dr. Baldwin's concerning upstarts: We don't care to eat toadstools
7 that think they are truffles.
8 -- Mark Twain, "Pudd'nhead Wilson's Calendar"
9
10 Sheriff Chameleotoptor sighed with an air of weary sadness, and then
11 turned to Doppelgutt and said 'The Senator must really have been on a
12 bender this time -- he left a party in Cleveland, Ohio, at 11:30 last
13 night, and they found his car this morning in the smokestack of a British
14 aircraft carrier in the Formosa Straits.'
15 -- Grand Panjandrum's Special Award, 1985 Bulwer-Lytton
匹配句首 '^'
➤ grep -ni '^A' fortune
1:All generalizations are false, including this one.
14:aircraft carrier in the Formosa Straits.'
-n 的意思是显示行号
匹配句尾 '$'
➤ grep -ni '\.$' fortune
1:All generalizations are false, including this one.
4:very thin paper.
7:that think they are truffles.
这里的 '.$' 是以 . 字符结尾的意思, 中间的反斜杠是逃逸字符,起转义的效果
匹配空行 '^$'
➤ grep '^$' fortune -n
5:
9:
任意单个字符 '.'
➤ grep -n '.re' fortune
1:All generalizations are false, including this one.
3:Many pages make a thick book, except for pocket Bibles which are on very
6:Remark of Dr. Baldwin's concerning upstarts: We don't care to eat toadstools
7:that think they are truffles.
11:turned to Doppelgutt and said 'The Senator must really have been on a
\b 的意思是单词分界线,也许是空格,也许是tab
➤ grep -n '\b.re\b' fortune
1:All generalizations are false, including this one.
3:Many pages make a thick book, except for pocket Bibles which are on very
7:that think they are truffles.
零次或多次重复 '*'
➤ grep -n 'l*' fortune
1:All generalizations are false, including this one.
2: -- Mark Twain
3:Many pages make a thick book, except for pocket Bibles which are on very
4:very thin paper.
5:
6:Remark of Dr. Baldwin's concerning upstarts: We don't care to eat toadstools
7:that think they are truffles.
8: -- Mark Twain, "Pudd'nhead Wilson's Calendar"
9:
10:Sheriff Chameleotoptor sighed with an air of weary sadness, and then
11:turned to Doppelgutt and said 'The Senator must really have been on a
12:bender this time -- he left a party in Cleveland, Ohio, at 11:30 last
13:night, and they found his car this morning in the smokestack of a British
14:aircraft carrier in the Formosa Straits.'
15: -- Grand Panjandrum's Special Award, 1985 Bulwer-Lytton
显示的不是很好,因为没有高亮什么的.
其实这一部分完全可以当做正则来讲, 毕竟正则才是核心, grep只是一个工具, 怎么用,还是看你的能力如何了.
曾经看过一个30分钟入门正则表达式, 个人感觉挺不错的, 因为我也是从那里入的门, 所以也推荐看这一部分的人也去搜下那个, 作者写的够简单易懂了.
这一段写的有点长, 但是, 当你学会正则的时候你就会发现, 这东西真棒! (这是我BB的, 跟原作者无关哈…)