0

I'm trying to read a .csr file into a string, but I don't want the first and last line of the file.

I've tried reading the file into a string and then splitting it into an array, but I can't get the syntax to work.

I've also tried reading it into a string and then stripping away the first and last line (they never change), but I've had the same issue.

I'm new to bash and just need this script written, any help would be appreciated.

The file is test.csr and looks like this:

-----BEGIN CERTIFICATE REQUEST-----
TESTESTESTESTESTESTSETESTEESSTSETESTTESTES
TESTESTESTESTESTESTSETESTEESSTSETESTTESTES
...
-----END CERTIFICATE REQUEST-----

As an attempt for stripping I used

csrFile=`cat server.csr`
#echo "$csrFile"
#csrFile=${csrFile##*-----BEGIN CERTIFICATE REQUEST-----  }
#csrFile=${csrFile%% -----END CERTIFICATE REQUEST-----*}
#echo "$csrFile"

But when I echoed this out, the entire string was still intact

My attempt for splitting into an array

readarray -t my_array <<<"$csrFile"
echo "$my_array"
echo "$csrFile"
( IFS=$'\n'; echo "${csrFile[*]}" )

But this didn't print anything out

peterjwolski
  • 153
  • 2
  • 10
  • Possible duplicate: [Bash working code to delete first or last line from file](https://stackoverflow.com/q/8234711/3776858) – Cyrus Aug 23 '19 at 10:45

2 Answers2

1

sed would be ideal for this job.

To strip off the first and final lines, use

sed '1d;$d' server.csr

Or if you'd like to be more precise, try

sed '/-----\(BEGIN\|END\) CERTIFICATE REQUEST-----/d'  server.csr

To read the result into a variable, use the shell $() syntax:

csrfile=$(sed '/-----\(BEGIN\|END\) CERTIFICATE REQUEST-----/d'  server.csr)
Jon
  • 3,573
  • 2
  • 17
  • 24
  • Hi, thanks for this, how can I read the sed into a variable? my attempt is: csrString = sed '/-----BEGIN CERTIFICATE REQUEST-----/d;/-----END CERTIFICATE REQUEST-----/d' server.csr echo "$csrString" – peterjwolski Aug 23 '19 at 10:50
  • Managed it with csrFilteredString=$(echo "$a" | sed '/-----BEGIN CERTIFICATE REQUEST-----/d;/-----END CERTIFICATE REQUEST-----/d' server.csr) echo "$csrFilteredString" – peterjwolski Aug 23 '19 at 10:54
0

A more portable way would be to use tool that actually can read CSR, like openssl:

openssl req -in server.csr -outform der | base64 -w64

-outform der encodes the CSR into binary (actually ASN1)

base64 -w64 gets it back to base64 with 64 characters per line

oliv
  • 12,690
  • 25
  • 45