linux_grep命令的用法

本文详细介绍了grep命令的基本用法,包括如何在文件中搜索特定字符串、列出含有特定字符串的文件名和进程、不区分大小写的搜索、反选搜索、输出行号、统计匹配行数以及结合其他命令如sort、sed进行更复杂的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

grep命令的用法

grep:基于行的文本搜索工具

#比如说,file的内容是:
[root@localhost ~]$ cat filename
this is a textline for test
this filename is filename
just for Test

基本用法

# 比如 需要列出某文件中包含字符串'test'的行,命令:
[root@localhost ~]$ cat filename|grep 'test'
this is a textline for test

# 直接使用grep+字符串+文件名做匹配  和上面命令效果是一样的
[root@localhost ~]$ grep 'test' filename
this is a textline for test

# 列出当前文件夹下所有含'test'字符串的文件名和其匹配行
[root@localhost ~]$ grep 'test' ./*
./filename:this is a textline for test

# 列出包含字符串'name'的文件名
[root@localhost ~]$ ls |grep 'name'
filename

# 列出包含字符串'name'的进程
[root@localhost ~]$ ps -ef |grep 'name'

-i 不区分大小写

# grep 搜索默认区分大小写,还可以加上-i参数不区分大小写
[root@localhost ~]$ cat filename|grep -i 'test'
this is a textline for test
just for Test

-v 反选

# grep 还可以加上-v参数 表示反选
[root@localhost ~]$ cat filename|grep -v 'test'
this filename is filename
just for Test

[root@localhost ~]$ cat filename|grep -vi 'test'
this filename is filename

-n 输出行号

[root@localhost ~]$ cat filename|grep -v 'test'
2:this filename is filename
3:just for Test

-c 统计匹配的行数

# 同一行多次匹配 不重复计数。只计匹配到的行的个数
[root@localhost ~]$ cat filename|grep -n 'file'
1

结合sort还可以对结果进行排序

# sort 默认按字符大小比较来排序 -r表示逆序 
# sed -n取消全部输出
# sed -n '2p'表示仅输出第2行,'1,3p'则输出1-3行
[root@localhost ~]$ grep -i 'test' ./* |sort -r |sed -n '2p'
./filename:this is a textline for test
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值