Regex match in Bash if instruction does not work

Below is a small part of a larger script that I am working on, but below it gives me a lot of pain that makes a part of a larger script malfunction. The goal is to check if the variable has a string value corresponding to red hat or red hat . If so, change the variable name to redhat . But this does not quite match the regex that I used.

 getos="red hat" rh_reg="[rR]ed[:space:].*[Hh]at" if [ "$getos" =~ "$rh_reg" ]; then getos="redhat" fi echo $getos 

Any help would be greatly appreciated.

+5
source share
2 answers

Here you can find a few things.

So just

 getos="red hat" rh_reg="[rR]ed[[:space:]]*[Hh]at" if [[ "$getos" =~ $rh_reg ]]; then getos="redhat" fi; echo "$getos" 

or enable compat31 option from extended shell option

 shopt -s compat31 getos="red hat" rh_reg="[rR]ed[[:space:]]*[Hh]at" if [[ "$getos" =~ "$rh_reg" ]]; then getos="redhat" fi echo "$getos" shopt -u compat31 

But instead of messing around with these shell options, just use the advanced test operator [[ with a variable string without quotes.

+6
source

There are two problems:

Replace first:

 rh_reg="[rR]ed[:space:].*[Hh]at" 

WITH

 rh_reg="[rR]ed[[:space:]]*[Hh]at" 

A character class such as [:space:] only works in square brackets. In addition, it seems that you want to combine zero or more spaces, and this is [[:space:]]* not [[:space:]].* . The latter will correspond to a space followed by zero or most.

Secondly, replace:

 [ "$getos" =~ "$rh_reg" ] 

WITH

 [[ "$getos" =~ $rh_reg ]] 

Regular expression matching requires the bash extended test: [[...]] . The standard POSIX test [...] does not have this feature. Also, in bash, regular expressions work only if they are not quotation marks.

Examples:

 $ rh_reg='[rR]ed[[:space:]]*[Hh]at' $ getos="red Hat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos redhat $ getos="RedHat"; [[ "$getos" =~ $rh_reg ]] && getos="redhat"; echo $getos redhat 
+4
source

Source: https://habr.com/ru/post/1275388/


All Articles