点击(此处)折叠或打开
-
[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
-
选项与参数:
-
-a :将 binary 文件以 text 文件的方式搜寻数据
-
-c :计算找到 '搜寻字符串' 的次数
-
-i :忽略大小写的不同,所以大小写视为相同
-
-n :顺便输出行号
-
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
- --color=auto :可以将找到的关键词部分加上颜色的显示喔!
点击(此处)折叠或打开
-
# dmesg | grep -n -A3 -B2 --color=auto 'eth'
-
用 dmesg 列出核心信息,再以 grep 找出内含 eth 那行,在关键字所在行的前两行与后三行也一起捉出来显示
-
-
# grep -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件
-
# grep -l -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件
-
-
使用正则表达式
-
# grep -n 't[ae]st' regular_express.txt
-
需要的字串是『tast』或『test』两个字串
-
-
# grep -n '[^g]oo' regular_express.txt
-
想要搜索到有 oo 的行,但不想要 oo 前面有 g
-
-
# grep -n 'o\{2\}' regular_express.txt
-
要找到两个 o 的字串
-
-
-
# grep -n 'go\{2,5\}g' regular_express.txt
- 要找出 g 后面接 2 到 5 个 o ,然后再接一个 g 的字串
点击(此处)折叠或打开
-
扩展grep(grep -E 或者 egrep):
-
对于标准grep,如果在扩展元字符前面加\,grep会自动启用扩展选项-E。
-
-
# egrep 'NW|EA' testfile
-
打印所有包含NW或EA的行
-
-
# egrep '3+' testfile
-
# grep -E '3+' testfile
-
# grep '3\+' testfile
-
搜索所有包含一个或多个3的行。
-
-
-
# egrep '2\.?[0-9]' testfile
-
# grep -E '2\.?[0-9]' testfile
-
# grep '2\.\?[0-9]' testfile
-
#首先含有2字符,其后紧跟着0个或1个点,后面再是0和9之间的数字。
-
-
-
# egrep '(no)+' testfile
-
# grep -E '(no)+' testfile
- # grep '\(no\)\+' testfile #3个命令返回相同结果,