一、作用

  1. 用于查找文件里符合条件的字符串

二、选项

  • -l # 只列出匹配行所在文件的文件名 # grep -l “for” ./*.sh
  • -h # 不显示文件名
  • -i # 忽略大小写
  • -n # 在每一行中加上相对行号
  • -v # 反向查找 # grep -Ev “^#|^$” /etc/ssh/sshd_config
  • -E # 使用扩展正则表达式 # grep -Ev “^#|^$|^;” /etc/ssh/sshd_config
  • -w # 精确匹配 # grep -w “port” /etc/ssh/sshd_config
  • -wc # 精确匹配次数
  • -o # 查询所有匹配字段 # grep -o “port” /etc/ssh/sshd_config
  • -P # 使用perl正则表达式
  • -A3 # 打印匹配行和下三行
  • -B3 # 打印匹配行和上三行
  • -C3 # 打印匹配行和上下三行
  • -q 不显示任何信息

    三、实例

    [root@localhost ~]# grep -l  "" ./*.sh  /work/*.sh
    ./16.sh
    ....省略
    /work/sd.sh
    
    ```shell [root@localhost ~]# grep -v “a” /usr/local/nginx/conf/nginx.conf

    这个配置文件放nginx服务的基本配置

    1.启动用户 2.cpu亲和力 3.err_log位置 4.pid位置 5.文件最大描述符

    6.工作模式 7.http{}放置全局优化内容如:log格式 gzip压缩 开启子配置文件

user www www; worker_rlimit_nofile 51200;

指定nginx工作模式

events { use epoll; worker_connections 51200; }

```shell
[root@localhost ~]# grep -w 'off' /usr/local/nginx/conf/nginx.conf
        multi_accept off;
        accept_mutex off;
        server_tokens off;
        access_log off;
[root@localhost ~]# grep -E "acc|pff|log" /usr/local/nginx/conf/nginx.conf
# 1.启动用户   2.cpu亲和力   3.err_log位置   4.pid位置   5.文件最大描述符
# 6.工作模式   7.http{}放置全局优化内容如:log格式 gzip压缩 开启子配置文件
error_log  /usr/local/nginx/logs/nginx_error.log  crit;
pid        /usr/local/nginx/logs/nginx.pid;
        multi_accept off;
        accept_mutex off;
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
        access_log off;
        grep -w 'a\>' txt                            # 精确匹配字符串
        grep -i "a" txt                              # 大小写敏感
        grep  "a[bB]" txt                            # 同时匹配大小写
        grep '[0-9]\{3\}' txt                        # 查找0-9重复三次的所在行
        grep -E "word1|word2|word3"   file           # 任意条件匹配
        grep word1 file | grep word2 |grep word3     # 同时匹配三个
   grep用于if判断{

            if echo abc | grep "a"  > /dev/null 2>&1
            then
                echo "abc"
            else
                echo "null"
            fi

            echo "abc" | grep "a" > /dev/null 2>&1
            if [ $? == 0 ]
            then
                echo "abc"
            else
                echo "null"
            fi

        }
}