参数说明
--color:将匹配内容高亮显示(即使用的secureCRT,也能很明显的看出高亮)
-v:反向匹配,即不匹配
-i :忽略大小写
-c:打印匹配的行数(非个数)
-n:在匹配结果前打印所在行的行号
-w:匹配单词,即只搜索包含整个单词的行。例如搜索test时,会将test123、wertest等也匹配,加上-w参数后,就只匹配test。
-o:仅仅显示匹配出的字符,而不是匹配出的行(用正则表达式时比较方便)
-e [pattern]: --regexp=[pattern] 正则表达式,一般用在表达式 "-" 开头或者需要使用多个正则表达式的情景
-C [num] --context=[num] 打印前后 n 行
-B [num] --before-context=[num] 打印前 n 行
-A [num] --after-context=[num] 打印后 n 行
-m [num] --max-count=[num] 最多匹配 n 行后停止
-R/-r:两个个参数作用相同,都是递归搜索子目录下文件内容
-H:强制输出文件名(该参数无需手动添加,默认即为强制输出文件名的)
-h:禁止输出文件名(搜寻所个文件时,默认将匹配行所在文件的文件名也打印出来,其实是默认包含-H参数)
-l:只打印有匹配结果的文件名
-L:只打印没有匹配结果的文件名
举例
grep ifm30 /etc/passwd
grep --color ifm30 /etc/passwd
grep -v ifm30 /etc/passwd
grep -i ifm30 /etc/passwd
grep -iv ifm30 /etc/passwd
grep -ci ifm30 /etc/passwd
grep -civ ifm30 /etc/passwd
grep -ni ifm30 /etc/passwd
grep -niv ifm30 /etc/passwd
grep -o i.*30 /etc/passwd
grep --color -iw ifm30 /etc/passwd
grep -ivw ifm30 /etc/passwd
grep -r ifm30 /etc/
grep -R ifm30 /etc/
grep -Rh ifm30 /etc/
grep -rh ifm30 /etc/
grep -RL ifm30 /etc/
grep -Rl ifm30 /etc/
正则表达式
grep -o i.*30 /etc/passwd
grep ^ifm30 /etc/passwd
grep ifm30$ /etc/passwd
grep ^ifm30$ /etc/passwd
grep ^$ /etc/passwd
grep '\<b.t\>' 文件名
grep '^..$' 文件名
grep '^\.[0-9]' 文件名
grep '192.168.1.254' /etc/hosts
grep '192\.168\.1\.254' /etc/hosts
grep 'foo[0-9][0-9]' 文件名
grep '[A-Za-z]' 文件名
grep [wn] 文件名
技巧
grep 'warning\|error\|critical' /var/log/messages
$ grep -w 'warning\|error\|critical' /var/log/messages
- 所有的
grep -E
都可以用egrep
来替换;所有的grep -F
都可以用fgrep
来替换
grep -Erw "ifm30|ifm40" /etc/
grep -E "v{2}" 文件名
grep -E 'co{1,2}l' 文件名
grep -E 'c{3,}' 文件名
grep "[[:digit:]]\{2\}[ -]\?[[:digit:]]\{10\}" 文件名