0

DPHPV = /usr/local/nginx/conf/php81-remi.conf;

I am unable to figure out how to match a string that contains any 2 digits:

if [[ "$DPHPV" =~ *"php[:digit:][:digit:]-remi.conf"* ]]
5
  • 1
    If you are trying to match files with names like php53-remi.conf then one way to do it is if [[ $DPHPV == php[[:digit:]][[:digit:]]-remi.conf ]]. Commented Jun 26, 2022 at 19:04
  • 3
    Use: [[ "$DPHPV" =~ php[0-9][0-9]-remi.conf ]] Commented Jun 26, 2022 at 19:05
  • 1
    The whole purpose of quoting in Bash is to suppress the special significance that certain characters or character sequences would otherwise have, such as for globbing. Commented Jun 26, 2022 at 19:52
  • 1
    You're also mixing syntax for globbing, by using *, but =~ requires regular expressions, where the equivalent would be .*. Regexes alo aren't anchored, so the */.* can just be skipped. Glob expressions (==/= instead of =~) require matching the entire string, so there you would need the * Commented Jun 26, 2022 at 19:54
  • The part of the rhs of the =~ , which is written between quotes, is interpreted as a literal match, not as a regular expression. Further, the lone * in front of the regex does not have any meaning as regex. You can see it when doing i.e. a [[ x =~ * ]], which does not match. Commented Jun 27, 2022 at 6:35

1 Answer 1

1

You are not using the right regex here as * is a quantifier in regex, not a placeholder for any text.

Actually, you do not need a regex, you may use a mere glob pattern like

if [[ "$DPHPV" == *php[[:digit:]][[:digit:]]-remi.conf ]]

Note

  • == - enables glob matching
  • *php[[:digit:]][[:digit:]]-remi.conf - matches any text with *, then matches php, then two digits (note that the POSIX character classes must be used inside bracket expressions), and then -rem.conf at the end of string. See the online demo:
#!/bin/bash
DPHPV='/usr/local/nginx/conf/php81-remi.conf'
if [[ "$DPHPV" == *php[[:digit:]][[:digit:]]-remi.conf ]]; then
    echo yes;
else
    echo no;
fi

Output: yes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.