softwareRat
softwareRat

Reputation: 55

SED replace in bash between round brackets

I want to use sed to check if some string match to a pattern and then save that match into a variable:

function tst2(){
    string='cms(1.2;1.5;1.3)'
    regex='cms\(.*\)'
    echo -e $string

    if [[ $string =~ $regex ]]
    then
        myVar=$(echo -e $string | sed "s/cms\(.*\)/\1/g")
        echo $myVar
    else
        echo "too badd!!!"
    fi
}

Console output:

[user@home~]$ tst2
cms(1.2;1.5;1.3)
(1.2;1.5;1.3)

I would like myVar to become "1.2;1.5;1.3" (without the round brackets)

Upvotes: 0

Views: 748

Answers (2)

AwkMan
AwkMan

Reputation: 670

This is a faster way without having to use sed. It uses the bash builtin BASH_REMATCH variable filled when the =~ operator is used:

function tst2(){
    string='cms(1.2;1.5;1.3)'
    regex='cms\((.*)\)'
    echo -e $string

    if [[ $string =~ $regex ]]
    then
       echo ${BASH_REMATCH[1]}
    else
       echo "too badd!!!"
    fi
}

Upvotes: 2

gilez
gilez

Reputation: 679

myVar=$(expr $string : $regex)

This will do what you want (using the shell's builtin expr). You need to adjust your regex though, to:

regex='cms(\(.*\))'

That matches the brackets yet doesn't include them in the result.

Upvotes: 1

Related Questions