1

I'm trying to filter a part of a file that holds 2 digital certificates. Basically, I want the first part (let's say Cert1) and not the second part (Cert2).

Content of the file is:

-----BEGIN CERTIFICATE-----
AAAA
AAAA
ETC
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AAAA
AAAA
ETC
-----END CERTIFICATE-----

I was under the impression that this would give me the content of Cert1 (the first part between the first BEGIN and the first END):

cat /etc/nginx/cert.pem | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

For some reason, though, it still presents me all the content between the second BEGIN and the second END (basically, nothing changes; all content is the same).

Any pointers?

2

You can use the following sed command for this task

sed '/-----END CERTIFICATE-----/q' /etc/nginx/cert.pem

q is an exit code which instructs sed to quit. Therefore sed will print from the beginning of the file and quit when the pattern '-----END CERTIFICATE-----' is encountered. This causes it to stop at the end of the first certificate.

Also there is no need to use a pipe to redirect the output of cat to sed. Simply specify the filename in the sed command.

Source - http://www.theunixschool.com/2011/09/sed-selective-printing.html

| improve this answer | |
4

You were almost there:

sed -ne '
   /-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p      # got the range, ok
   /-END CERTIFICATE-/q                            # bailing out soon as the cert end seen
' /etc/nginx/cert.pem

But note that the cert begin and end marker lines are part of the output as well.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.