Linux的grep命令

grep

grep(global regular expression print)的首字母縮寫,是一個強大的文本搜索工具。

grep命令的語法格式:

grep [options] [regular expression] [filename...]
#[options]是命令選項
#[regular expression]是正則表達式
#[filename]是數據來源的文本文件

[options]命令選項
還有一些的命令可以通過man grep去查看

-v 顯示所有不匹配的模式的行答應出來
-i 忽略大小寫敏感
-n 輸出是打印行號
-l 輸出包含搜索文件的文件名
-L 輸出不包含搜索文件的文件名
-E 匹配正則表達式

Examples
爲了更好的展示例子,我先vim 11.txt

[root@VM_79_126_centos ~]# cat 11.txt
Hello,world
hello,World
Hello,World
hello,world
[root@VM_79_126_centos ~]# grep -v "world" 11.txt
hello,World
Hello,World
#顯示除了沒有字符串world的行
[root@VM_79_126_centos ~]# grep -i  "Hello" 11.txt 
Hello,world
hello,World
Hello,World
hello,world
#這是忽略大小寫的結果
[root@VM_79_126_centos ~]# grep -n "world" 11.txt  
1:Hello,world
4:hello,world
#顯示行號
[root@VM_79_126_centos ~]# grep -l 'hello' *
grep: 11: Is a directory
11.txt
#顯示出文件名了
[root@VM_79_126_centos ~]# grep -L 'hello' *
grep: 11: Is a directory
11
1.sh
anaconda-ks.cfg
grep: beautifulsoup4-4.3.2: Is a directory
beautifulsoup4-4.3.2
beautifulsoup4-4.3.2.tar.gz
CREDITS
grep: Desktop: Is a directory
Desktop
files_of_user.sh
line_record.sh
#顯示出其他的文件了

[regular expression]

\ 忽略正則表達式中特殊字符的原有含義。
^匹配行的開始
$匹配行的結尾
^$空白行
.匹配任意單個字符
*匹配緊挨在前面的字符任意次(0,1,多次)
.*匹配任意長度的任意字符
\?匹配緊挨在前面的字符0次或1次
\{m,n\}匹配其前面的字符至少m次,至多n次
[]匹配指定範圍內的任意單個字符
[^]匹配指定範圍外的任意單個字符
[:digit:]所有數字, 相當於0-9, [0-9]---> [[:digit:]]
[:lower:]所有的小寫字母
[:upper:]所有的大寫字母
[:alpha:]所有的字母
[:alnum:]相當於0-9a-zA-Z
[:space:]空白字符
\d 所有數字,-->[0-9]
\D 數字以外的所有其他字符-->[^0-9]
\w 所有大小寫字母和數字及下畫線-->[a-zA-Z0-9]
\W 除了字母、數字、下劃線以外的所有其他字符 -->[^a-zA-Z0-9]
\s 任何空白字符,相當於[\f\n\r\t\v]
\S 空白字符以外的任何字符,相當於[^\f\n\r\t\v]

Example1
先vim http_address.txt

#先vim http_address.txt
[root@VM_79_126_centos ~]# cat http_address.txt   
http://www.xijiximo.cn
https://www.xijiximo.cn
httpss://www.xijiximo.cn
[root@VM_79_126_centos ~]# grep -E "[Hh][Tt][Tt][Pp][Ss]?://[a-zA-Z0-9./-]+" http_address.txt 
http://www.xijiximo.cn
https://www.xijiximo.cn
#

Example2

#先vim dates.txt
[root@VM_79_126_centos ~]# cat dates.txt 
22-7-1982
6/2/08
2016/6/17
7/7/7
[root@VM_79_126_centos ~]# grep -E "[0-9]{1,2}[-/][0-9]{1,2}[/-][0-9]{2,4}" dates.txt 
22-7-1982
6/2/08
2016/6/17

Example3

#先vim ip_adress.txt
[root@VM_79_126_centos ~]# cat ip_adress.txt 
265.234.456.123
123.123.123.123
23.34.45.56
7.7.7.7
1234.123.123.1234
[root@VM_79_126_centos ~]# grep -E "\b((([0-9]{1,2})|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]{1,2})|(1[0-9]{2})
|(2[0-4][0-9])|(25[0-5]))\b" ip_adress.txt 
123.123.123.123
23.34.45.56
7.7.7.7

( 寫於2016年6月17日,http://blog.csdn.net/bzd_111

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章