1

Requirement is to find a string from txt file and store it to variable.

file look like this(rsa.txt)

Encrypting String
... Input string        : Test_123
... Encrypted string    : $ENC(JEVOQyhZbVpkQmM0L3ArT2c4M05TZks5TmxRPT1+KQ==)

Required output (variable name : encstring):

encstring = $ENC(JEVOQyhZbVpkQmM0L3ArT2c4M05TZks5TmxRPT1+KQ==)

I tried below code but showing no result

encstring=$(grep -oE '$ENC[^()]*==)' <<< rsa.txt)

1
  • 1
    You are searching for an occurance of $ENC which is not followed by an open or closed parenthesis. However, in your input file, there is an open parenthese after $ENC. Commented Apr 6, 2021 at 9:26

4 Answers 4

4

With awk, could you please try following. Simply, search for string /Encrypted string along with a condition to check if last field of that line has $ENC in it then last field for that line by using $NF.

encstring=$(awk '/Encrypted string/ && $NF~/\$ENC/{print $NF}'
Sign up to request clarification or add additional context in comments.

Comments

3

You can use

encstring=$(sed -n 's/.*\(\$ENC(.*)\).*/\1/p' rsa.txt)
# OR
encstring=$(grep -oP '\$ENC\(.*?\)' rsa.txt)

See an online demo:

s='Encrypting String
... Input string        : Test_123
... Encrypted string    : $ENC(JEVOQyhZbVpkQmM0L3ArT2c4M05TZks5TmxRPT1+KQ==)'
encstring=$(sed -n 's/.*\(\$ENC(.*)\).*/\1/p' <<< "$s")
echo "$encstring"
# => $ENC(JEVOQyhZbVpkQmM0L3ArT2c4M05TZks5TmxRPT1+KQ==)

The sed -n 's/.*\(\$ENC(.*)\).*/\1/p' command does the following:

  • -n suppresses the default line output
  • s/.*\(\$ENC(.*)\).*/\1/ - finds any text, then captures $ENC(...) into Group 1 and then matches the rest of the string, and replaces the match with the Group 1 value
  • p - prints the result of the substitution.

The grep -oP '\$ENC\(.*?\)' command extracts all $ENC(...) matches, with any chars, as few as possible, between ( and ).

Comments

2

You are searching for ENC which is followed by 0 or more occurances of something which is not an open or closed parenthesis. However, in your input file, there is an open parenthese after ENC. Therefore [^()]* matches the null string. After this you expect the string ==). This would match only for the input ENC==)`.

Comments

0

You need to escape $ as \$ as it means "end of string" with -E

Comments

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.