shell 如何使用Linux脚本反转给定CER文件的证书块?

crcmnpdw  于 2023-06-24  发布在  Shell
关注(0)|答案(2)|浏览(124)

如何使用Linux脚本(即awk、sed等)?
假设我有一个名为mycert.cer的文件,它看起来像:

-----BEGIN CERTIFICATE-----
this is sentence1
this is sentence2
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence3
this is sentence4
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence5
this is sentence6
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence7
this is sentence8
-----END CERTIFICATE-----

我希望输出看起来像这样:

-----BEGIN CERTIFICATE-----
this is sentence7
this is sentence8
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence5
this is sentence6
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence3
this is sentence4
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence1
this is sentence2
-----END CERTIFICATE-----

我尝试了以下方法:

tac -s'-----BEGIN CERTIFICATE-----' mycert.cer | awk '/-----BEGIN CERTIFICATE-----/, /-----END CERTIFICATE-----/'

但此命令给出以下错误输出:

-----BEGIN CERTIFICATE-----
this is sentence3
this is sentence4
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence1
this is sentence2
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE----------BEGIN CERTIFICATE-----

我该如何修改命令以获得所需的输出?

ux6nzvsh

ux6nzvsh1#

使用任意awk加tac:

$ tac mysert.cer | awk '
    { cert = $0 ORS cert }
    /BEGIN CERT/ { printf "%s", cert; cert="" }
'
-----BEGIN CERTIFICATE-----
this is sentence7
this is sentence8
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence5
this is sentence6
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence3
this is sentence4
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence1
this is sentence2
-----END CERTIFICATE-----

或者只是awk:

$ awk '
    { cert = cert $0 ORS }
    /END CERT/ { certs[++numCerts] = cert; cert="" }
    END { for (i=numCerts; i>=1; i--) printf "%s", certs[i] }
' mycert.cer
-----BEGIN CERTIFICATE-----
this is sentence7
this is sentence8
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence5
this is sentence6
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence3
this is sentence4
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
this is sentence1
this is sentence2
-----END CERTIFICATE-----
kuhbmx9i

kuhbmx9i2#

在awk中:

awk 'BEGIN{RS="\1";ORS=FS="-----END CERTIFICATE-----\n"}{while(--NF)print $NF}' file
# or slightly longer
awk -v RS="\1" -v FS="-----END CERTIFICATE-----\n" '{while(--NF)printf "%s",$NF FS}' file

# or you ever find an awk that doesn't allow changing NF (I haven't)
# change action to for(i=NF;--i;)print $i resp printf "%s%,$i FS

在perl中:

perl -n0777e 'map{print}reverse split $\="-----END CERTIFICATE-----\n"' file

这两种方法都将整个文件视为一个“记录”,如果你的awk不是GNU(现在很少见,但并非未知),它可能会因为文件太大而失败。

相关问题