Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Note : This is not really a question because I already found the answer but since I didn't find it easily here I will post it so that it can benefit others.

Question : How to read a concatenated PEM file as the one used by apache/mod_ssl directive SSLCACertificateFile ?

Answer (source) :

cat $file|awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'
share|improve this question
up vote 8 down vote accepted

This was previously answered on StackOverflow :

awk '
  split_after == 1 {n++;split_after=0}
  /-----END CERTIFICATE-----/ {split_after=1}
  {print > "cert" n ".pem"}' < $file
share|improve this answer
Works on Linux only, fails on FreeBSD. – Michael-O Jan 7 '15 at 22:07
Inspired by this I've created an awk script that splits out certs and keys into separate files: – JinnKo Mar 23 '15 at 18:12

The awk snippet works for extracting the different parts, but you still need to know which section is the key / cert / chain. I needed to extract a specific section, and found this on the OpenSSL mailinglist:

# Extract key
openssl pkey -in foo.pem -out foo-key.pem

# Extract chain
openssl crl2pkcs7 -nocrl -certfile foo.pem |
  openssl pkcs7 -print_certs -out foo-chain.pem

# Extract cert
openssl x509 -in foo.pem -outform DER -out foo-cert.pem
share|improve this answer
nice command set :) I'll keep it for future use, but in my use case above, I'm working with a cert-only file containing 50+ CA certs ==> no pkey nor chain – Cerber Mar 20 '15 at 12:42

Also worth noting that PEM files are just a collection of keys/certificates inside BEGIN/END blocks, so it's pretty easy to just cut/paste if it's just a single file with one or two interesting entities...

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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