Skip to content

Grep概述

希望通过linux的命令在文件中或其他命令结果中,统计(计算次数).

比如:统计/var/log/secure文件中Failed password出现的次数. 拆分

  • 第一个里程碑:过滤出包含Failed password的行:grep.
  • 第二个里程碑:命令的结果通过管道传递给其他命令:管道.
  • 第三个里程碑:通过命令统计次数:wc -l.
  • 在文件或命令的结果中,找出你要的或不要的(排除)的内容
  • grep命令,Linux三剑客之一,排第三,擅长过滤

Grep 常见参数

grep命令选项说明
-i(忽略)ignorecase 过滤的时候不区分大小写
-nline number过滤出内容并显示行号
-r递归过滤
-e用于指定一个或多个匹配模式。它允许你在查找文本时使用多个不同的正则表达式模式
-v对行进行取反
-E(egrep)扩展的正则表达式
-w用于匹配整个单词
-c统计字符串的次数
-o显示匹配过程

案例1使用grep过滤需要找的内容

shell
[root@kylin-xlj ~ 15:43]# grep  'port' /etc/ssh/sshd_config 
# If you want to change the port on a SELinux system, you have to tell
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
# WARNING: 'UsePAM no' is not supported in kylin and may cause several
# national algorithm standards supports

案例2使用grep -i 过滤内容且不区分大小写

shell
[root@kylin-xlj ~ 15:43]# grep -i 'port' /etc/ssh/sshd_config 
# If you want to change the port on a SELinux system, you have to tell
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
Port 22399
# WARNING: 'UsePAM no' is not supported in kylin and may cause several
#GatewayPorts no
GatewayPorts no
# national algorithm standards supports

案例3使用grep -n 过滤时候显示内容的行号,也可以搭配 -i 选项

shell
[root@kylin-xlj ~ 15:53]# grep -in 'port' /etc/ssh/sshd_config 
13:# If you want to change the port on a SELinux system, you have to tell
15:# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
17:Port 22399
95:# WARNING: 'UsePAM no' is not supported in kylin and may cause several
101:#GatewayPorts no
160:GatewayPorts no
166:# national algorithm standards supports
  • 在 Linux 系统中为 grep 设置别名并使其在执行时携带颜色参数的方法:
  • alias grep='grep --color=auto' 临时
  • 'grep --color=auto' 是新的命令形式,其中 --color=auto 会使 grep 在输出时根据匹配的内容自动添加颜色,使其更易于查看。
  • 别名添加到 shell 配置文件(永久有效):

echo "alias grep='grep --color=auto'" >> ~/.bashrc:使用 echo 命令将别名的定义添加到相应的配置文件(.bashrc.zshrc)的末尾。

source ~/.bashrcsource ~/.zshrc:重新加载配置文件,使新添加的别名立即生效。

感谢阅读,欢迎交流!