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>

2
  • 1
    Please add your desired output (no description, no images, no links) for that sample input to your question (no comment). Commented Dec 9, 2021 at 6:09
  • 3
    grep -Pzo '(?<=public_key=#STARTKEY#)[\s\S]*(?=#ENDKEY#)' file ? Commented Dec 9, 2021 at 6:12

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't support blanks lines. But while allowed, one is extremely unlikely to encounter any. So this is probably not a problem.
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.

3 Comments

I would use ([^#]*) instead of (.*), then strip all non base64 characters (like newlines) from the match
@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.
Oh yes, of course perl has non greedy *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.