grep命令詳解:過濾來自乙個檔案或標準輸入匹配模式內容。
除了 grep 外,還有 egrep。egrep 是 grep 的擴充套件,相當於 grep -e。
usage: grep [option]... pattern [file]...
選項描述
-e,--extended-regexp
模式是擴充套件正規表示式(ere)
-i,--ignore-case
忽略大小寫
-n,--line-number
列印行號
-o,--only-matching
只列印匹配的內容
-c,--count
只列印每個檔案匹配的行數
-b,--before-context=num
列印匹配的前幾行
-a,--after-context=num
列印匹配的後幾行
-c,--context=num
列印匹配的前後幾行
--color[=when]
匹配的字型顏色
-v,--invert-match
列印不匹配的行
[root@ken ~]# echo "this is ken this is ken" | grep -i 'ken'
this is ken this is ken
[root@ken ~]# echo "this is ken this is ken" | grep 'ken'
this is ken this is ken
2. -n,列印行號
[root@ken ~]# grep -n 'root' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
10:operator:x:11:0:operator:/root:/sbin/nologin
3. -o,只列印匹配的內容
[root@ken ~]# echo "this is ken this is ken" | grep -o 'ken'
ken[root@ken ~]# echo "this is ken this is ken" | grep 'ken'
this is ken this is ken
4. -c,列印檔案匹配的行數
[root@ken ~]# grep -c 'root' /etc/passwd
2[root@ken ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
5. -b,列印匹配的前幾行
[root@ken ~]# grep -b 3 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
--shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
6.-a,列印匹配的後幾行
[root@ken ~]# grep -a 3 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
--operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:ftp user:/var/ftp:/sbin/nologin
nobody:x:99:99:nobody:/:/sbin/nologin
7.-c,列印匹配的前後幾行
[root@ken ~]# grep -c 3 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
--shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:ftp user:/var/ftp:/sbin/nologin
nobody:x:99:99:nobody:/:/sbin/nologin
8. --color,在centos7中已經預設為 grep --color,在centos6中需要加上--color才會顯示顏色
[root@ken ~]# alias grep
alias grep='grep --color=auto'
9. -v, 列印不匹配的行
[root@ken ~]# echo -e "hi\nthis is ken\nncie to meet you\nbye " | grep -v 'ken'
hincie to meet you
bye
shell指令碼 內容查詢之grep命令
grep命令可以檢索檔案中包含關鍵字 可以使用正則 的行,預設區分大小寫。ubuntu ubuntu test cat test.txt this is linux this is linux this is mysql this is mysql ubuntu ubuntu test grep l...
Shell指令碼中find和grep命令的區別
在shell指令碼中find 和 grep 同樣都是搜尋命令。find 命令用於在系統中搜尋符合條件的檔名,如果需要模糊查詢,則使用萬用字元進行匹配。搜尋時檔名是完全匹配的。例如 root localhost touch abc 建立檔案abc root localhost touch abcd 建...
shell指令碼學習(二) grep
1.grep egrep c 列印符合要求的行數 n 在輸出符合要求的行的同時連同行號一起輸出 v 列印不符合要求的行 r 會把目錄下面所有的檔案全部遍歷一遍 i 忽略大小寫 2.例子介紹 grep n root 1.txt grep n v root 1.txt 過濾出所有包含數字行 grep n...