Grep Perl正则表达式和捕获组

时间:2017-08-07 18:01:09

标签: regex bash perl

我正在尝试使用此命令获取SSl证书信息:

openssl s_client -connect gcm-http.googleapis.com:443

将返回SSL证书信息。我正在尝试grep -P,但却无法弄清楚1)正确的正则表达式,以及2)如何实际让Grep返回。到目前为止,带有以下正则表达式的grep命令不返回任何内容。

以下是我正在操作的信息:

(More unrelated data - Truncated)
---
Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.googleapis.com
   i:/C=US/O=Google Inc/CN=Google Internet Authority G2
 1 s:/C=US/O=Google Inc/CN=Google Internet Authority G2
   i:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
 2 s:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
   i:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority
---
Server certificate

-----BEGIN CERTIFICATE-----
MIIE3TCCA8WgAwIBAgIISZPzqn6Rx/0wDQYJKoZIhvcNAQELBQAwSTELMAkGA1UE
BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
cm5ldCBBdXRob3JpdHkgRzIwHhcNMTcwNzI1MDgyOTQ0WhcNMTcxMDE3MDgyNzAw
WjBqMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEZMBcGA1UEAwwQKi5n
b29nbGVhcGlzLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL50
UZFxROM8NwIcSTC9V6XAJkoCcW+xuLtYFUbP+6zomzzxYXtTjh+s33XvtaHoNk1S
WxBqSX+0YsS1RHzwWT4KwJpkEyrqJ/WDtKs3hQY27Lng6IZmAYomoRXNZBWgXdQ0
sBddBU9/HtpKu0RpL6qM+7y7Xpp8KHilqPfjvtc8eljvOAdU3RA3w1p2JIov+F5n
sbD1bMqq3Xx6wbT7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v+SHCXVT3rRHGD+
wA==
-----END CERTIFICATE-----

....
(More unrelated data - Truncated)

我已尝试过这两种正则表达式:

grep -P '((?:-+BEGIN CERTIFICATE-+\n)(.+\n)*(?:-+END CERTIFICATE-+))'

grep -P '(?:-+BEGIN CERTIFICATE-+\n)(.+\n)(?:-+END CERTIFICATE-+)'

基本上,我只想返回证书本身,而不是----BEGIN CERTIFICATE---------END CERTIFICATE-----

我知道可能有更好的方法来制作正则表达式,但我已经在regexr.comregex101.com

上测试了它(并且可以正常工作)

如果Grep成功捕获它,那么echo $1正在返回任何内容。

3 个答案:

答案 0 :(得分:6)

我没有设法使用grep,但有一个Perl解决方案:

perl -0777 -n -e \
    'print $1 if /-+BEGIN CERTIFICATE-+\n(.+\n)*-+END CERTIFICATE-+/s' \
    cert.txt

这将在第一个“BEGIN ...”和最后一个“END ...”之间打印所有

<强>更新

@brian d foy写了关于“独占触发器操作符”an article。根据那篇文章,这也有效:

perl -n -e \
    'print if ($rc = /-+BEGIN CERTIFICATE/ .. /-+END CERTIFICATE-+/ and $rc !~ /(^1|E0)$/)' cert.txt 

答案 1 :(得分:6)

仅供记录,这里只提取证书的grep命令:

grep -zoPe '--BEGIN.*\n\K[^-]+' file | head -c-1

诀窍是使用-z / --null-data选项(输入行以\0终止,而不是换行符)。我们还使用PCRE和PCRE的特殊转义序列the reset match start \K,这会使任何先前匹配的字符不包含在最终匹配序列中(我们只需要--BEGIN...\n之后和{{}之前的部分{1}})。

-...将移除最后一个字符,即旧版head -c-1换行符(例如GNU grep v2.12)和< em> null byte 用于较新的grep s(例如GNU grep v2.25)。

答案 2 :(得分:1)

使用sed

sed -n '/----BEGIN CERTIFICATE-----/,/----END CERTIFICATE-----/ p' inputfile |
   sed '1d;$d'

编辑: 错过&#34;证书&#34;

或者使用awk:

awk '/----END CERTIFICATE-----/ {pr=0;}
     pr==1 {print}
     /----BEGIN CERTIFICATE-----/ {pr=1;}' inputfile