Home > Net >  Find occurence of string in a text and extract the value
Find occurence of string in a text and extract the value

Time:11-03

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.

CodePudding user response:

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)

CodePudding user response:

if [${env} == *"ral"* ];

This does not work because the shell does file name globbing, as if you did ls *ral*, so you're looking at a list of file names (if anything matches) or the original term *ral* if nothing matches.

You can use a regular expression in bash:

if [[ "$var" =~ .*ral.* ]]
then
    echo "$var matches"
fi

To capture, use parens and access the capture via BASH_REMATCH where the group count in the regex is the number in the array index.

if [[ "$var" =~ -(ral.[0-9] )- ]]
then
    echo "$var matches: ${BASH_REMATCH[1]}"
fi
  •  Tags:  
  • bash
  • Related