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 Ias 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