Monday, February 21, 2022

[SOLVED] Find occurence of string in a text and extract the value

Issue

I need to do the following in bash.

I have,

env = prod/abcd-ral-5645-test123 I need to check if the string ral exists in env and if it exists I need to extract the value ral-5645 to a different variable.

I have tried to find the occurence of ral as below, but stuck in extracting the text ral-5645

if [${env} == *"ral"* ];
then
   echo "It's there."
fi

Any help is much appreciated.


Solution

What about:

grep -o "ral-[0-9]*" env

Explanation:

  • [0-9] means whatever character from 0 to 9 (every possible digit).
  • [0-9]* means whatever number of digits
  • -o means "only show the pattern (see man grep)


Answered By - Dominique
Answer Checked By - Cary Denson (WPSolving Admin)