LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   RegEx in if condition. How? (https://www.linuxquestions.org/questions/linux-newbie-8/regex-in-if-condition-how-4175636889/)

ddenial 08-22-2018 01:47 PM

RegEx in if condition. How?
 
Hello

I trying to RegEx mpg and mpeg in 'if' condition. It is not working.

Code:

if [[ $VAR == "mp4" || $VAR =~ "mp[e]?g" ]] ; then
  echo "Do something"
fi

assuming VAR could have mpg or mpeg value.

How to do that?

Thanks

astrogeek 08-22-2018 02:02 PM

Assuming you are using the bash shell, remove the quotes from the regex expression. Quoting all or parts of the regex causes the quoted parts to be matched as a string (man bash of course).

Code:

if [[ $VAR == "mp4" || $VAR =~ mp[e]?g ]] ; then
  echo "Do something"
fi

I am not sure how this applies to other shells, but likely similar, see the respective man pages as always.

ddenial 08-22-2018 02:18 PM

Quote:

Originally Posted by astrogeek (Post 5894523)
Assuming you are using the bash shell, remove the quotes from the regex expression. Quoting all or parts of the regex causes the quoted parts to be matched as a string (man bash of course).

Code:

if [[ $VAR == "mp4" || $VAR =~ mp[e]?g ]] ; then
  echo "Do something"
fi

I am not sure how this applies to other shells, but likely similar, see the respective man pages as always.

That worked perfectly. Thanks.

l0f4r0 08-23-2018 03:09 AM

Quote:

Originally Posted by ddenial (Post 5894519)
Code:

if [[ $VAR == "mp4" || $VAR =~ "mp[e]?g" ]] ; then
  echo "Do something"
fi


By the way, square brackets are not necessary around "e" as there is only one character inside.
So:
Code:

$VAR =~ "mp[e]?g"
can be changed with:
Code:

$VAR =~ "mpe?g"

ddenial 08-23-2018 08:59 AM

Quote:

Originally Posted by l0f4r0 (Post 5894732)
By the way, square brackets are not necessary around "e" as there is only one character inside.
So:
Code:

$VAR =~ "mp[e]?g"
can be changed with:
Code:

$VAR =~ "mpe?g"

Thanks

MadeInGermany 08-23-2018 03:38 PM

A glob match (==) is "anchored" by default, so you might want to put anchors on the RE match (=~)
Code:

if [[ $VAR == mp4 || $VAR =~ ^mpe?g$ ]]
Compare with the following, where both matches are "floating"
Code:

if [[ $VAR == *mp4* || $VAR =~ mpe?g ]]
Last but no least, the RE is an ERE, and is more powerful than the glob.
Often you can do everything in one ERE
Code:

if [[ $VAR =~ ^(mp4|mpe?g)$ ]]

syg00 08-23-2018 07:18 PM

All good advice, but I wonder how expensive the regex engine is ?. Might be better off using the OR test if there is a large disparity in favour of "mp4" and the test can take advantage of short-circuiting.
Just idle musings ...

pan64 08-24-2018 01:07 AM

yes, a case would be probably better:
Code:

case $VAR in
    mp4)
    mpeg)
    mpg)
    *)
esac



All times are GMT -5. The time now is 11:00 PM.