一、前言
grep是功能強大的文本處理工具,全稱:global search regular expression and print out the line,grep一行一行使用正則表達式匹配文本,之后對匹配到的文本整行顯示(除非使用特定的選項取反,如 grep -v)。
二、grep用法
grep命令用法:
grep [OPTIONS] PATTERN [FILE…]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE…]
為了使用grep用法,我們不得不先簡單學習下正則表達式
2.1、正則表達式用法
首先,我們要明白什么是正則表達式?所謂正則表達式就是使用單個字符串來描述、匹配一系列符合某個語法規則的字符串。正則表達式由一些普通字符和元字符組成。普通字符包括大小寫的字母和數字,而元字符則具有特殊的含義。
2.1.1、元字符用法
a:字符匹配
. | 匹配任意單個字符 | 例如:grep roo. /etc/passwd | |||||||
[] | 匹配指定范圍內的任意單個字符 | 例如:grep [ro] /etc/passwd | |||||||
[^] | 取反 | 例如:grep [^ro] /etc/passwd |
b:次數匹配
* | 匹配任意次數 | 例如: grep roo* /etc/passwd | |||||||
\? | 匹配其前面字符出現0或者1次 | 例如: grep roo\? /etc/passwd | |||||||
\{m\} | 匹配其前面字符出現m次 | 例如: grep ro\{2\} /etc/passwd | |||||||
\{m,\} | 匹配其前面字符最少出現m次 | 例如: grep ro\{2,\} /etc/passwd | |||||||
\{m,n\} | 匹配其前面字符最少出現m次,最多n次 | 例如: grep ro\{2,3\} /etc/passwd | |||||||
\{0,n\} | 匹配其前面字符最多n次 | 例如: grep ro\{0,2\} /etc/passwd |
c:位置錨定匹配
^ | 行首錨定符 | 例如:grep ^root /etc/passwd | |||||||
$ | 行尾錨定符 | 例如:grep shell$ /etc/passwd | |||||||
\< | 詞首錨定符 | 例如:grep \<root /etc/passwd | |||||||
\> | 詞尾錨定符 | 例如:grep shell\> /etc/passwd |
d:分組
\(\) | 分組,分組中模式匹配的內容可被引用 | 例如:grep \(root\).*\1 /etc/passwd |
e:引用
\# | 引用分組中第#個內容(#為數字) | 例如:grep \(root\).*\1 /etc/passwd |
2.2、grep常用的選項
-v | 反向選擇 | 例如:grep -v root /etc/passwd | |||||||
-o | 僅顯示匹配的字符串本身,而非所在行 | 例如:grep -o root /etc/passwd | |||||||
-i | 忽略大小寫 | 例如:grep -i root /etc/passwd | |||||||
-E | 支持使用擴展正則表達式 | 例如:grep -E (root).*\1 /etc/passwd | |||||||
-A | 后面n行 | 例如:grep -A 3 root /etc/passwd | |||||||
-B | 前面n行 | 例如:grep -B 3 mysql /etc/passwd | |||||||
-C | 前后各n行 | 例如:grep -C 3 mysql /etc/passwd |
三、總結
grep用法其實并不難,難在正則表達式的使用,grep是非常強大的文本搜索工具,熟練使用grep工具有利于我們后續對文本文件的處理。
原創文章,作者:成吉思汗,如若轉載,請注明出處:http://www.www58058.com/7190