二、grep文本搜索工具

时间:2021-08-21
本文章向大家介绍二、grep文本搜索工具,主要包括二、grep文本搜索工具使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

grep命令作为Unix中用于文本搜索的神奇工具,能够接受正则表达式,生成各种格式的输出。除此外,它还有大量有趣的选项。

# 搜索包含特定模式的文本行:
[root@centos8 ~]#grep pattern filename

# 可以从stdin中读取:
[root@centos8 ~]#echo -e "this is a word\nnext line" | grep word
this is a word

# 单个grep命令也可以对多个文件进行搜索:
[root@centos8 ~]#grep "a_txt" file1,file2,file3 ...

# 用--color选项可以在输出行中着重标记出匹配到的单词:
[root@centos8 ~]#grep word a.txt --color=auto
nihoa word hell okd old edu

# grep命令只解释match_txt中的某些特殊字符。如果要使用正则表达式,需要添加-E选项————这意味着使用扩展正则表达式。或者也可以使用默认允许正则表达式的grep命令————egrep。
[root@centos8 ~]#grep -E "[a-z]+" filename
[root@centos8 ~]#egrep  "[a-z]+" filename

# 使用选项-o 可以只输出文件中匹配到的文本部分:
[root@centos8 ~]#echo this is a line. | egrep -o "[a-z]+\."
line.
# 不加 o 的输出结果
[root@centos8 ~]#echo this is a line. | egrep  "[a-z]+\."
this is a line.

# 选项 -v 要打印除包含match_txt行之外的所有行:
[root@centos8 ~]#grep -v math_txt filename

# 选项 -c 统计文件或文本中包含匹配字符串的行数:
[root@centos8 ~]#grep -c "word" a.txt
# 注意:-c 只是统计匹配行的数量,并不是匹配的次数,例如:
[root@centos8 ~]#echo -e "1 2 3 4\nhello\n5 6" > a.txt 
[root@centos8 ~]#cat a.txt 
1 2 3 4
hello
5 6
[root@centos8 ~]#egrep -c  "[0-9]" a.txt 
2

# 搜索多个文件并找出匹配文本位于哪一个文件中:
[root@centos8 ~]#grep -l linux a.txt b.txt 
a.txt
b.txt
和-l 相反的选项是-L,它会返回一个不匹配的文件列表

原文地址:https://www.cnblogs.com/studyhub/p/15170563.html