Linux常用命令之grep命令
作者简介
听雨:一名在一线从事多年研发的程序员,从事网站后台开发,熟悉java技术栈,对前端技术也有研究,同时也是一名骑行爱好者。
Darren:一个工作经验用了N年的,资深划水人士,除了工作无其他爱好
口号:记录在开发中遇到日常问题、棘手问题的解法和思路
常用命令之grep
背景介绍
grep
是 “Global Regular Expression Print” 的缩写。它通过使用正则表达式来搜索文本文件中的特定模式,并输出包含该模式的行。对于查找文件中的某些字符或者正则匹配的值非常奏效。
常用参数
参数 | 解释 |
---|---|
-i | 忽略大小写匹配 |
-r | 递归搜索模式 |
-v | 不包含匹配文本所有行 |
-c | 计数匹配的行数 |
-n | 显示所有匹配行以及行号 |
-w | 只匹配整个单词 |
参考示例
example.txt
root@master:~/temp# cat example.txt
hello
Hello
Hello world
hello world
hell
666888
W2132
hello2
演示目录
root@master:~/temp# tree
.
├── ansible
│ └── hosts
├── dockerfile
│ └── Dockerfile
├── example.txt
├── prometheus
│ ├── console_libraries -> /usr/share/prometheus/console_libraries
│ ├── consoles -> /usr/share/prometheus/consoles/
│ └── prometheus.yml
└── test
└── example.txt
4 directories, 7 files
root@master:~/temp#
忽略大小写
root@master:~/temp# grep -i "hello" example.txt
hello
Hello
Hello world
hello world
hello2
root@master:~/temp#
递归搜索模式
root@master:~/temp# grep -r "hello" *
example.txt:hello
example.txt:hello world
example.txt:hello2
test/example.txt:hello
test/example.txt:hello world
root@master:~/temp#
不匹配文本所有行
root@master:~/temp# grep -v "hello" example.txt
Hello
Hello world
hell
666888
W2132
root@master:~/temp#
匹配计数
root@master:~/temp# grep -c "hello" example.txt
3
root@master:~/temp#
显示所有匹配行以及行号
root@master:~/temp# grep -n "hello" example.txt
1:hello
4:hello world
8:hello2
匹配整个单词
root@master:~/temp# grep -w "hello" example.txt
hello
hello world
还可以匹配正则表达式
匹配以 “hello” 开头的行
root@master:~/temp# grep "^hello" example.txt
hello
hello world
hello2
root@master:~/temp#
匹配以 “hello” 结尾的行
root@master:~/temp# grep "hello$" example.txt
hello
root@master:~/temp#
我还喜欢用一个命令, -3
意味着匹配值的上下3行,用于匹配关键字查上下文是否有错的情况
root@master:~/temp# grep -3 666 example.txt
Hello world
hello world
hell
666888
W2132
hello2
root@master:~/temp#
总结
grep是强大的匹配搜索工具,可以和其他ls或管道符配合使用,可以做到搜索的效果。掌握grep可以大大提高检索效率,可以说是查日志的神器。
参考:《Linux常用命令自学手册》