0

I need to extract the public key in the shell script, Not sure how to use this. I am new to shell script. https://regex101.com/r/SXDEaU/1

Content of the file:

public_key=#STARTKEY#<public key base64 encoded>#ENDKEY#

Regex: /public_key=#STARTKEY#(.*)#ENDKEY#/s

Since the key is base64 encoded, it is a multiline string.

Desired output: <public key base64 encoded>

anubhava
  • 761,203
  • 64
  • 569
  • 643
nick
  • 17
  • 1
  • 5
  • 1
    Please add your desired output (no description, no images, no links) for that sample input to your question (no comment). – Cyrus Dec 09 '21 at 06:09
  • 3
    `grep -Pzo '(?<=public_key=#STARTKEY#)[\s\S]*(?=#ENDKEY#)' file` ? – tshiono Dec 09 '21 at 06:12

2 Answers2

2

With awk using its RS variable and setting it to paragraph mode please try following code.

awk -v RS= 'match($0,/public_key=#STARTKEY#.*#ENDKEY#/){print substr($0,RSTART+21,RLENGTH-29)}'  Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • That doesn't support blanks lines. But while allowed, one is extremely unlikely to encounter any. So this is probably not a problem. – ikegami Dec 09 '21 at 19:33
0
perl -M5.010 -0777ne'say for /public_key=#STARTKEY#(.*?)#ENDKEY#/s' file

The key is -0777 which causes the entire file to be read in as one line.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • I would use `([^#]*)` instead of `(.*)`, then strip all non base64 characters (like newlines) from the match – Fravadona Dec 09 '21 at 19:32
  • @Fravadona, I didn't look at the pattern; I just showed how to use it as requested. `[^#]*` isn't correct, That should be `(?:(?!#ENDKEY#).)*`. But `.*?` would do just as well here, and it would be better than `.*`. Adjusted answer. /// Stripping non-base64 characters wasn't requested, isn't always desirable, and can't be done without knowing which flavour of base64 is being used. – ikegami Dec 09 '21 at 19:37
  • Oh yes, of course perl has non greedy `*` – Fravadona Dec 09 '21 at 19:39