Pensu
Pensu

Reputation: 3619

How to extract a part of the string between two characters in bash?

I am trying to extract a part of the string using bash. The string is in the format:

peeyush (>= 5) peeyush (<= 7)

Now I want to extract the numbers in the braces in two variables. Something like

echo $var1
>=5
echo $var2
<=7

Or even better if it is possible to extract the numbers in min and max format from the string?

Any pointers are appreciated.

Upvotes: 1

Views: 81

Answers (1)

anubhava
anubhava

Reputation: 785146

Use this grep:

s='peeyush (>= 5) peeyush (<= 7)'

unset var1 var2
while read -r p; do
    [[ -z "$var1" ]] && var1="$p" || var2="$p"
done < <(grep -oP '\(\K[^)]+' <<< "$s")

echo "$var1"
>= 5
echo "$var2"
<= 7

Upvotes: 1

Related Questions