• grep命令的-P选项及使用方法简介


    man grep的时候有一个-P选项,文档上的英文如下所示:

    OPTIONS
       Generic Program Information
           --help Output a usage message and exit.

           -V, --version
                  Output the version number of grep and exit.

       Pattern Syntax
           -E, --extended-regexp
                  Interpret PATTERNS as extended regular  expressions  (EREs,  see
                  below).

           -F, --fixed-strings
                  Interpret PATTERNS as fixed strings, not regular expressions.

           -G, --basic-regexp
                  Interpret  PATTERNS  as  basic  regular  expressions  (BREs, see
                  below).  This is the default.

           -P, --perl-regexp
                  Interpret I  as  Perl-compatible  regular  expressions
                  (PCREs).   This option is experimental when combined with the -z
                  (--null-data) option, and grep  -P  may  warn  of  unimplemented
                  features.

    中文翻译过来的意思是,-P或--perl-regexp选项能够让grep使用perl兼容的正则表达式语法(PCREs)。由于perl的正则更加多元化,能实现更加复杂的场景。

    正则表达式最典型的用法是,匹配指定字符串之间的字符。 比如:想要在一句话“Hello,my name is aming.”)中匹配中间的一段字符串“my name is” 能够以如下方式写正则表达式:

    echo "Hello, my name is aming." | grep -P '(?<=Hello, ).*(?= aming.)'

    命令运行结果如下:

    $ echo "Hello, my name is aming." | grep -P '(?<=Hello, ).*(?= aming.)'
    Hello, my name is aming.

    若是只须要匹配到的部分,还可以加上-o选项,如下所示:

    echo "Hello, my name is aming."| grep -Po '(?<=Hello, ).*(?= aming.)'

    命令运行结果如下:

    $ echo "Hello, my name is aming." | grep -P -o '(?<=Hello, ).*(?= aming.)'
    my name is

  • 相关阅读:
    Spring Cloud Feign
    WebRTC简介
    UE5的TimeLine的理解
    想学好C语言这些关键字不能少(深度解剖)
    短视频视频制作矩阵剪辑系统---源码,源代码独立搭建
    【网络安全的神秘世界】JavaScript
    因为做了这样的项目,成为了offer收割机!
    数据库-MySQL-基础(5)- DQL
    java八股文面试[数据库]——慢查询优化
    《30天吃掉那只 TensorFlow2.0》 一、TensorFlow的建模流程
  • 原文地址:https://blog.csdn.net/phmatthaus/article/details/126718629