linux grep 文档搜索命令
**grep 文本搜索工具 ** (global search regular expression(RE) and print out the line)
常用参数:
-w (word regexp)匹配整词 -x (line regexp)匹配整行 -i(ignore case) 不区分大小写 -E 使用正则表达式 -r 递归调用
-c (count)只输出匹配行数量 -n (line number) 显示匹配行及行号 -H 每一个匹配项显示文件名 -m (max num) 最大匹配次数 -o (only match) 只输出匹配项 -l 只打印包含搜索项的文件名
-A 打印匹配内容前num行 -B 打印匹配内容后num行 -C 打印匹配内容前后num行
测试文本内容,两个文件(a.txt,b.html)内容一致 * I am sailing, I am sailing home again 'cross the sea. I am sailing stormy waters, to be near you, to be free. I am flying, I am flying like a bird 'cross the sky. I am flying passing high clouds, to be near you, to be free. Can you hear me, can you hear me, through the dark night far away? I am dying, forever crying, to be with you; who can say? Can you hear me,*
#默认搜索
> grep "flying" a.txt
I am flying, I am flying
I am flying
#查看匹次数
> grep -c "am" a.txt
5
#打印匹配行号
> grep -n "am" a.txt
1:I am sailing, I am sailing
3:I am sailing stormy waters,
5:I am flying, I am flying
7:I am flying
14:I am dying,
#完全匹配单词,无输出
> grep -nw "sail" a.txt
#完全匹配单词
> grep -nw "sailing" a.txt
1:I am sailing, I am sailing
3:I am sailing stormy waters,
#匹配整行
> grep -nx "sailing" a.txt
> grep -nx "I am flying" a.txt
7:I am flying
#-i不区分大小写
> grep -n "AM" a.txt
> grep -ni "AM" a.txt
1:I am sailing, I am sailing
3:I am sailing stormy waters,
5:I am flying, I am flying
7:I am flying
14:I am dying,
#显示匹配文件名
> grep -H "am" a.txt
a.txt:I am sailing, I am sailing
a.txt:I am sailing stormy waters,
a.txt:I am flying, I am flying
a.txt:I am flying
a.txt:I am dying
#最大匹配2次结束
> grep -H -m2 "am" a.txt
a.txt:I am sailing, I am sailing
a.txt:I am sailing stormy waters,
#使用正则
> grep -E "fly+" a.txt
I am flying, I am flying
I am flying
#-o只显示匹配内容
> grep -E "fly\S+" -o a.txt
flying,
flying
flying
#显示匹配内容前后行控制
> grep -n "high" a.txt
8:passing high clouds,
#显示匹配内容的前三行
> grep -n -A3 "high" a.txt
8:passing high clouds,
9-to be near you,
10-to be free.
11-Can you hear me,
#显示匹配内容的后三行
> grep -n -B3 "high" a.txt
5-I am flying, I am flying
6-like a bird 'cross the sky.
7-I am flying
8:passing high clouds,
#显示匹配内容的前后三行
> grep -n -C3 "high" a.txt
5-I am flying, I am flying
6-like a bird 'cross the sky.
7-I am flying
8:passing high clouds,
9-to be near you,
10-to be free.
11-Can you hear me,
#-r递归查询
> grep -H "high" -r . --include *.txt
./a.txt:passing high clouds,
#查询多个匹配项
> grep -e "high" -e "near" a.txt
to be near you, to be free.
passing high clouds,
to be near you,
#显示匹配文件名
> grep -l "high" *
a.txt
b.html