【Linux常用命令】之grep命令

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常用命令自学手册》

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值