文本处理:grep
grep家族
grep: 在文件中全局查找指定的正则表达式,并打印所有包含该表达式的行
egrep:扩展的egrep,支持更多的正则表达式元字符
fgrep:固定grep(fixed grep),有时也被称作快速(fast grep),它按字面解释所有的字符
一、grep命令格式
grep [选项] PATTERN filename filename ...
$ grep 'root' /etc/passwd
$ grep -q 'hello world' /etc/passwd;echo $? # -q 静默输出
找到: grep返回的退出状态为0
没找到: grep返回的退出状态为1
找不到指定文件: grep返回的退出状态为2
grep 程序的输入可以来自标准输入或管道,而不仅仅是文件,例如:
$ grep 'root'
$ ps aux | grep "ssh"
$ ll | grep '^d'
$ grep 'root' /etc/passwd /etc/shadow /etc/group
二、grep使用的元字符
grep: 使用基本元字符集 ^, $, ., *, [], [^], \< \>, \(\), \{\}, \+, \|
egrep(或grep -E): 使用扩展元字符集 ?, +, {}, |, ()
注: grep也可以使用扩展集中的元字符,仅需要对这些元字符前置一个反斜线
\w 所有字母与数字,称为'字符'[a-zA-Z0-9] 'l[a-Z0-9]*ve' 'l\w*ve'
\W 所有字母与数字之外的字符,称为'非字符' 'love[^a-Z0-9]' 'love\W+'
\b 词边界 '\<love\>' '\blove\b'
三、grep示例
grep -E 或 egrep
$ egrep "NW" datafile
$ egrep "NW" d*
$ egrep "^n" datafile
$ egrep "4$" datafile
$ egrep TB Savage datafile
$ egrep 'TB Savage' datafile
$ egrep '5\..' datafile
$ egrep '\.5' datafile
$ egrep '^[we]' datafile
$ egrep '[^0-9]' datafile
$ egrep '[a-z][a-z] [a-z]' datafile
$ egrep 'ss* ' datafile
$ egrep '[a-z]{9}' datafile
$ egrep '\<north\>' datafile
$ egrep '\<north' datafile
$ egrep '\<[a-r].*n\>' datafile
$ egrep '^n\w*\W' datafile
$ egrep '\bnorth\b' datafile
$ egrep 'NW|EA' datafile
$ egrep '3+' datafile
$ egrep '2\.?[0-9]' datafile
$ egrep '(no)+' datafile
$ egrep 'S(h|u)' datafile
$ egrep 'Sh|u' datafile
四、grep选项
选项 | 介绍 |
-i, --ignore-case | 忽略大小写 |
-l, --files-with-matches | 只列出匹配行所在的文件名 |
-n, --line-number | 在每一行前面加上它在文件中的相对行号 |
-c, --count | 显示成功匹配的行数 |
-s, --no-messages | 禁止显示文件不存在或文件不可读的错误信息 |
-q, --quit, --silent | 静默输出 |
-v, --invert-match | 反向查找,只显示不匹配的行 |
-R, -r, --recursive | 递归针对目录 |
--color | 颜色 |
-o, --only-matching | 只显示匹配的内容 |
-B, --before-context=NUM | print NUM lines of leading context |
-A, --after-context=NUM | print NUM lines of trailing context |
-C, --context=NUM | print NUM lines of output context |
示例:
~ » egrep "ifcfg" /etc/* 文件
~ » grep -R "ifcfg" /etc 目录
# 多文件进行匹配
~ » egrep 'root' /etc/passwd /etc/hosts
# 只列出匹配行所在的文件名
~ » egrep -l 'root' /etc/passwd /etc/hosts
/etc/passwd
# 显示匹配到的行号
~ » egrep -n 'root' /etc/passwd /etc/hosts
/etc/passwd:12:root:*:0:0:System Administrator:/var/root:/bin/sh
~ » vim /etc/passwd +12
# \转义
~ » useradd --help|egrep "\-g\>"
作业:
#!/bin/bash
# 判断输入的IP是否合规
function ip(){
if [[ $1 =~ ([0-9]{1,3}\.){3}[0-9]{1,3} ]];then
echo "ip is ok"
else
echo "ip is error"
fi
}
ip $1