grep是Linux中最常用的"文本處理工具"之一,grep與sed、awk合稱為Linux中的三劍客。
grep的全稱為: Global search Regular Expression and Print out the line
全稱中的"Global search"為全局搜索之意。
全稱中的"Regular Expression"表示正則表達式。
所以,從grep的全稱中可以了解到,grep是一個可以利用"正則表達式"進行"全局搜索"的工具,grep會在文本文件中按照指定的正則進行全局搜索,並將搜索出的行打印出來。
當然,不使用正則表達式時也可以使用grep,但是當grep與正則表達式結合在一起時,威力更強大。
實例文件:
Now stand you on the top of happy hours,
And many maiden gardens, yet unset,
With virtuous wish would bear your living flowers,
Much liker than your painted counterfeit:
So should the lines of life that life repair
Which this time's pencil or my pupil pen,
Neither in inward worth nor outward fair
Can make you live yourself in eyes of me.
To give away yourself keeps yourself still,
And you must live, drawn by your own sweet skill.
1.最簡單字符串查詢
查詢包含you的句子:
要顯示所屬的行,使用-n選選項
查詢完整的單詞,使用-w選項
忽略大小寫使用-i選項
通過使用-c選項,計算單詞出現的個數:
2.正則表達式的使用

查詢包含an以及后邊的任意字符
3.反向選擇
排除選擇的字符使用-v選項
查詢沒有and的行,並顯示行號
4.查詢選擇行的前后行
查詢選中行的后一行,使用-A[num] num可以是一個數字
查詢選中行的前一行,使用-B[num] num是一個數字
查詢選中行的上下幾行,使用-C[num] num是一個數字,表示要選中的行數