Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching one of several possible characters in a string

Tags:

bash

scripting

In a bash (version 3.2.48) script I get a string that can be something like:

'XY'
' Y'
'YY'
etc

So, I have either an alphabetic character OR a space (first slot), then the relevant character (second slot). I tried some variation (without grep, sed, ...) like:

if [[ $string =~ ([[:space]]{1}|[[:alpha:]]{1})M ]]; then

and

if [[ $string =~ (\s{1}|.{1})M ]]; then

but my solutions did not always work correctly (matching correctly every combination).

like image 521
Max Avatar asked Jan 15 '23 22:01

Max


2 Answers

This should work for you:

if [[ $string =~ [[:space:][:alpha:]]M ]]; then
like image 199
Dennis Williamson Avatar answered Jan 28 '23 15:01

Dennis Williamson


if [[ ${string:1:1} == "M" ]]; then
    echo Heureka
fi

or (if you want to do it with patterns)

if [[ $string =~ ([[:space:]]|[[:alpha:]])M ]]; then
    echo Heureka
fi

or (even simpler)

if [[ $string == ?M ]]; then
    echo Heureka
fi
like image 32
nohillside Avatar answered Jan 28 '23 15:01

nohillside