1 关于grep,用于查找匹配字符串,通常有三种,grep,egrep,fgrep
grep [option] pattern file1 file2
[liuliancao@liuliancao exp]$ cat t1.txt hello,this is liuliancao both liulian and cao. if there is a tree, i will cut down it. [liuliancao@liuliancao exp]$ cat t2.txt hello,this is a bear. i hate ones who cut down my trees. and i like walking around the forest.
普通用法 [liuliancao@liuliancao exp]$ grep tree t1.txt t2.txt t1.txt:if there is a tree, t2.txt:my trees. and i like [liuliancao@liuliancao exp]$ sudo netstat -tunlp | grep 8000 tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 19828/python
取反,不显示匹配到的行 [liuliancao@liuliancao exp]$ grep -v tree t1.txt hello,this is liuliancao both liulian and cao. i will cut down it.
不区分大小写,使用-i选项 [liuliancao@liuliancao exp]$ grep TREE t1.txt [liuliancao@liuliancao exp]$ grep -i TREE t1.txt if there is a tree,
多个文件的情况下,不输出文件名的匹配 [liuliancao@liuliancao exp]$ grep -i TREE t1.txt t2.txt t1.txt:if there is a tree, t2.txt:my trees. and i like [liuliancao@liuliancao exp]$ grep -ih TREE t1.txt t2.txt if there is a tree, my trees. and i like
显示匹配的文件名 [liuliancao@liuliancao exp]$ grep -l liuliancao t1.txt t2.txt t1.txt
显示匹配的行号 [liuliancao@liuliancao exp]$ grep -n liuliancao t1.txt t2.txt t1.txt:1:hello,this is liuliancao
显示匹配的次数-c [liuliancao@liuliancao exp]$ fgrep -ch liuliancao t1.txt 1
使用fgrep或者grep -F意味着抛弃模式,匹配的是纯字符串 [liuliancao@liuliancao exp]$ fgrep it. t1.txt t2.txt t1.txt:i will cut down it.
使用egrep或者grep -E意味着使用扩展的正则表达式,可以使用分组,捕获,|,or,+等 [liuliancao@liuliancao exp]$ egrep -v '^$|#' /etc/my.cnf [mysqld] basedir = /usr/local/mysql datadir = /home/mysql port = 3306 server_id = 1 socket = /tmp/mysql.sock sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [liuliancao@liuliancao exp]$ grep -vE '^$|#' /etc/my.cnf [mysqld] basedir = /usr/local/mysql datadir = /home/mysql port = 3306 server_id = 1 socket = /tmp/mysql.sock sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
最后需要注意的是grep的括号捕获的部分是需要\(pattern\)的而后可以反向引用\1,大括号同理,相对于普通的正则,但是[ab]表示a或b不用反斜线