<Linux> grep文件搜索

来源:互联网 发布:windows永久免费vps 编辑:程序博客网 时间:2024/05/17 23:04

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



This is the first string.
0 0
原创粉丝点击