<Linux> grep文件搜索

grep 是Global search Regular Expression的缩写。用于文件的字符串搜索。支持正则表达式。


使用方法:

grep [Options] Pattern FILE[s]


Options常用的有以下:

-c   只输出匹配行的计数。
-i   不区分大小写(只适用于单字符)。
-l   查询多文件时只输出包含匹配字符的文件名。

-n   显示匹配行及行号。
-v   显示不包含匹配文本的所有行。

-e 正则表达式

-w  以单词为单位匹配

-A  显示匹配行和之后的N行

-B  显示匹配行和之前的N行

-C 显示匹配行和之前之后的N行


Pattern:

  可使用正则表达式

FILE[s]:

  可单个文件,也可多个,也可以是正则表达式的文件。


示例:

测试文本test.txt:

This is the first string.
THIS IS THE SECOND STRING.
third line..
the end;


普通搜索:

$ grep "string" test.txt

This is the first string.


不区分大小写:

$ grep -i "string" test.txt

This is the first string.
THIS IS THE SECOND STRING.


显示行号:

$ grep -i -n "string" test.txt

1:This is the first string.
2:THIS IS THE SECOND STRING.


只显示匹配的行号:

$ grep -i -c "string" test.txt

2


以单词为单位搜索:

$ grep -w "is" test.txt

This is the first string.

$grep "is" test.txt

Thisis the first string.


显示匹配前后的N行:

$ grep -A 2 -w "is" test.txt   // 显示匹配之后的2行

This is the first string.
THIS IS THE SECOND STRING.
third line..

$ grep -B 2 -w "end" test.txt  // 显示匹配之前的2行

THIS IS THE SECOND STRING.
third line..
the end;

$grep -C 2 -w "IS" test.txt  // 显示匹配前后的2行,test.txt总共4行

This is the first string.
THIS IS THE SECOND STRING.
third line..
the end;


反搜索,显示不包括字符串的行

$ grep -n -i -v "this" test.txt
3:third line..
4:the end;

多个不匹配的条件:

$ grep -n -i -v -e "this" -e "the" test.txt
3:third line..


搜索多个文件:

$ grep  "include" *   // 当前目录下所有含有"include"的文件及匹配行, 加参数-l 只显示文件名

dll.c:#include <stdio.h>
gbtest.c:#include <stdio.h>
redir.txt:#include <stdio.h>
test.c:#include <stdio.h>


|管道作为输入:

$ ls | grep ".c"  搜索当前文件夹下.c文件

dll.c
gbtest.c
test.c


与find命令联合使用:

$ find . -type f -name \*.mk | xargs grep Dialer -in

 搜索文件夹下.mk结尾, 并包含Dialer字符串的文件.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值