linux grep命令与常用正则表达式


1  grep (General Regular Expression Parse)命令格式
格式: grep [option] pattern file
option: 
n (--line-number)             - 显示行号 
i (--ignore-case)               - 不区分大小写 
E ( --regexp=PATTERN)    - 使用扩展的正则元字符集,或使用egrep
l (--files-with-matches)     - 列出匹配的文件名 
v (--invert-match)            - 反向匹配  
r (--recursive)                  - 递归查找目录中的所有文件
2 常用正则表达式
基本元字符集
$ grep -n ^public t1.txt
$ grep -n public$ t1.txt
$ grep -n ^$ t1.txt
$ grep -n \<public t1.txt
$ grep -n '\<public' t1.txt
$ grep -n 'public\>' t1.txt
$ grep -n "\<public" t1.txt
$ grep -n ^.$ t1.txt
$ grep -n 11[MNX] t1.txt
$ grep -n 11[^MNX] t1.txt
$ grep -n go*d t1.txt
双引号与单引号区别,双引号不能抑制\与$字符
$ grep -n '\\' t1.txt
$ grep -n " \\\\" t1.txt
扩展元字符集
$ grep -nE go+d t1.txt
$ grep -nE 10{3}A t1.txt
$ grep -nE "10{2,4}A" t1.txt
$ grep -nE 10\{2,4\}A t1.txt
$ grep -nE '11A|B' t1.txt
$ grep -nE net\(works\)* t1.txt
3 grep中使用示例
使用通配符查询多个文件
$ grep -n test *.txt
反向匹配
$ ps aux | grep sshd | grep -v grep
递归搜索
$ grep -nr telnet /etc
只列出匹配的文件名
$ grep -l test *.txt
 
4 vi中使用正则表达式
在当前行中删除从aa到zz之间的所有字符
:s/aa.*zz//
在整个文件中的and替换成&
:1,$s/and/\&/g
在每一行的行首插入new
:1,$s/^/new/
在第2行到第5行末尾插入@@
:2,5s/$/@@/g
去掉行首的所有数字字符
:s/^[0-9]+//g
示例:交换参数
foo(10,7,2) foo(7,10,2)
foo(x+13,y-2,10) foo(y-2,x+13,10)
foo(bar(8),x+y+z,5) foo(x+y+z,bar(8),5)
:1,$s/foo(\([^,]*\),\([^,]*\),\([^\)]*))/foo(\2,\1,\3)/g

相关内容

    暂无相关文章