当前位置: 首页 > Linux

Linux文本搜索命令-grep

时间:2023-04-06 07:16:53 Linux

grep在命名的输入文件(如果没有命名文件,则为标准输入)中搜索包含与给定PATTERN匹配的行。默认情况下,grep打印匹配的整行。example1:搜索一个文件,最常用的模式[root@aliyun-hk1linux-shell-test]#grephellogrep1.shhelloexample2:递归搜索一个目录下的所有文件[root@aliyun-hk1linux-shell-test]#greppython2/etc/grep:/etc/:是一个目录[root@aliyun-hk1linux-shell-test]#grep-rpython2/etc//etc/rpm/macros.python:CFLAGS="%{optflags}"%{__python}%{py_setup}%{?py_setup_args}build--executable="%{__python2}%{py_shbang_opts}"%{?*}/etc/rpm/macros.python:if(string.starts(package,"python2-"))then/etc/rpm/macros.python:print("Provides:python2-"example3:Searchkeywordsfromastandardinput,searchfromapipeline[root@aliyun-hk1linux-shell-test]#ps-ef|greppythonroot80310Feb28?00:00:34/usr/bin/python-Es/usr/sbin/tuned-l-Proot2502724873021:34pts/000:00:00grep--color=autopython[root@aliyun-hk1linux-shell-test]#example4:搜索时忽略大小写,使用-i[root@aliyun-hk1linux-shell-test]#grep你好grep1.sh[root@aliyun-hk1linux-shell-test]#grep-i你好grep1.shhello[root@aliyun-hk1linux-shell-test]#ps-ef|grep-iPythonroot80310Feb28?00:00:34/usr/bin/python-Es/usr/sbin/tuned-l-Proot2505424873021:40pts/000:00:00grep--color=auto-iPython[root@aliyun-hk1linux-shell-test]#example5:要在搜索时排除某些关键字,请使用-v[root@aliyun-hk1linux-shell-test]#ps-ef|grep-iPythonroot80310Feb28?00:00:34/usr/bin/python-Es/usr/sbin/tuned-l-Proot2506324873021:42pts/000:00:00grep--color=auto-iPython[root@aliyun-hk1linux-shell-test]#ps-ef|grep-iPython|grep-vgreproot80310Feb28?00:00:34/usr/bin/python-Es/usr/sbin/tuned-l-P[root@aliyun-hk1linux-shell-test]#example6:搜索时使用正则表达式,-egrep–e"regularexample7:搜索结果只返回匹配的文件名,-l[root@aliyun-hk1linux-shell-test]#grep-ilHellogrep1.shgrep1.shexample8:搜索结果只返回不匹配的文件名,-L[root@aliyun-hk1linux-shell-test]#grep-irLpythongrep1.shgrep1.sh[root@aliyun-hk1linux-shell-test]#grep-irLhellogrep1.sh[root@aliyun-hk1linux-shell-test]#example9:结合find命令搜索日志或配置文件[root@aliyun-hk1linux-shell-test]#find/-name*.log|xargsgrep-il错误/var/log/yum.log/var/log/cloud-init.log/var/log/nginx/access.log/var/log/nginx/error.log/usr/local/share/aliyun-协助/1.0.1.259/log/aliyun_assist_update.log/usr/local/share/aliyun-assist/1.0.1.259/log/aliyun_assist_main.log/usr/share/doc/libjpeg-turbo-1.2.90/change.logexample10:搜索gz或tar.gz文件,使用zgrep[root@aliyun-hk1linux-shell-test]#zgrep-aihellogrep1.tar.gzecho1.shustarrootroothellohellogrep1.shustarrootroothelloworldhEllowordHElloworldhellosir[root@aliyun-hk1linux-shell-test]#zgrep-ihellogrep1.sh.gzhelloworldhEllowordHelloworld目录hellosir[root@aliyun-hk1linux-shell-test]#example11:更多参数请查看文档,mangrep