Regular expressions (Bash): verschil tussen versies
Naar navigatie springen
Naar zoeken springen
Regel 9: | Regel 9: | ||
I have the impression that regular expressions (regex) in Bash may not be the same as in MySQL, hence some more details in this article. | I have the impression that regular expressions (regex) in Bash may not be the same as in MySQL, hence some more details in this article. | ||
+ | |||
+ | == Match a substring == | ||
+ | |||
+ | Probably the easiest case - No special characters or whatever needed: | ||
+ | |||
+ | <pre> | ||
+ | i="blub"; [[ $i =~ blubber ]] && echo "i contains the substring 'blubber' " # False | ||
+ | i="blub"; [[ $i =~ blub ]] && echo "i contains the substring 'blub' " # True | ||
+ | </pre> | ||
== Match a single digit == | == Match a single digit == |
Versie van 29 sep 2022 12:05
To use regular expressions in Bash comparisons, use operator =~
, like
if [[ "$switches" =~ [f] ]]; then echo "f - Create folder structure" mappenstructuur=true fi
I have the impression that regular expressions (regex) in Bash may not be the same as in MySQL, hence some more details in this article.
Match a substring
Probably the easiest case - No special characters or whatever needed:
i="blub"; [[ $i =~ blubber ]] && echo "i contains the substring 'blubber' " # False i="blub"; [[ $i =~ blub ]] && echo "i contains the substring 'blub' " # True
Match a single digit
[]
denotes single character-comparison:
[[ $i =~ [2] ]] && echo "i contains '2'" [[ $i =~ [12] ]] && echo "i contains '1' and/or '2'"
Match all numbers or letters
[[ $i =~ [0-9] ]] && echo "i contains a number" i="blub"; [[ $i =~ [A-Z] ]] && echo "i contains at least one uppercase letter" # False i="BLUB"; [[ $i =~ [A-Z] ]] && echo "i contains at least one uppercase letter" # True i="blub"; [[ $i =~ [a-z] ]] && echo "i contains at least one lowercase letter" # True i="blub"; [[ $i =~ [a-zA-Z] ]] && echo "i contains at least one letter" # True
Sequences
^
: Beginning of the string$
: End of the string
i="BLuB"; [[ $i =~ ^[A-Z]+$ ]] && echo "i contains only capital letters" # False i="BLUB"; [[ $i =~ ^[A-Z]+$ ]] && echo "i contains only capital letters" # True