Linux grep 命令详解

目录

介绍

常用选项

示例


介绍

grep 命令全称(global regular expression) ,是用于查找文件里符合条件的字符串或正则表达式。

语法

grep [options] pattern [files]
#options  选项
#pattern  表示要查找的字符串或正则表达式。
#files    表示要查找的文件名,可以同时查找多个文件。

常用选项

-i忽略大小写进行匹配
-v反向查找,只打印不匹配的行
-n显示匹配行的行号
-r递归查找子目录中的文件
-l只打印匹配的文件名
-c只打印匹配的行数

更多选项参数可通过grep --help查看。

示例

1、在文件 test.txt 中查找字符串 "helloworld",并打印匹配的行:

[root@localhost shell]# cat test.txt
jksdjask
djaskjd
sdjkasj
helloworld
jskaj
skajs
ksaljks
skalsjkla;
kk
[root@localhost shell]# grep helloworld test.txt
helloworld

2、在文件夹 shell中递归查找所有文件中匹配正则表达式 "pattern" 的行,并打印匹配行所在的文件名和行号:

[root@localhost dir]# grep -r -n pattern /root/shell
/root/shell/test_3.txt:3:pattern
/root/shell/test_1.txt:5:pattern
/root/shell/dir/test_4.txt:2:pattern

3、在标准输入中查找字符串 "world",并只打印匹配的行数:

[root@localhost dir]# echo "hello world" | grep -c world
1

4、在当前目录中,查找后缀有 txt字样的文件中包含 hello 字符串的文件,并打印出该字符串的行:

[root@localhost shell]# grep hello *txt
file.txt:hello
test.txt:helloworld

5、以递归的方式查找符合条件的文件。例如,查找/root/shell目录下包含字符串hello的文件,并打印出该字符串所在行的内容:

[root@localhost shell]# grep -r hello /root/shell/
/root/shell/file.txt:hello
/root/shell/test.txt:helloworld

6.查找文件名中包含 test 的文件并且列出不包含pattern的行:

[root@localhost shell]# grep -v pattern *test*
test_1.txt:shj
test_1.txt:sjka
test_1.txt:sjakjs
test_1.txt:klas
test_1.txt:sakjs
test_1.txt:smkajs
test_1.txt:ksaj
test_1.txt:
test_3.txt:dnj
test_3.txt:dks
test_3.txt:dsjakdj
test_3.txt:dskd
test_3.txt:kjjdsa
test.txt:jksdjask
test.txt:djaskjd
test.txt:sdjkasj
test.txt:helloworld
test.txt:jskaj
test.txt:skajs
test.txt:ksaljks
test.txt:skalsjkla;
test.txt:kk

7.查找文件中以js结尾的行:

[root@localhost shell]# grep "js$" test_1.txt
sjakjs
sakjs
smkajs

8.查找文件中以k开头的行:

[root@localhost shell]# grep "^k" test_1.txt
klas
ksaj

9.匹配多个选项:

[root@localhost shell]# grep -e shj -e klas test_1.txt
shj
klas
# -e 逻辑or关系

10.在多个文件中查找以hello开头的行:

[root@localhost shell]# grep  "hello*" test_1.txt test_3.txt test.txt
test.txt:helloworld
[root@localhost shell]# grep  "^hello" test_1.txt test_3.txt test.txt
test.txt:helloworld

差不多就写到这里,关于grep的使用方法还有很多,后期再慢慢补充。如果你有意见或建议,请在评论区发表评论。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值