Extract variables values from command output Bash Shell -




in bash shell have command prints variable name , values such as:

hello mate variables: my_var1= value of first var my_var2= subvar1=27, subvar2=hello1 have day! 

the value of variables in output can contain characters =,commas,;,:.., expect find new line @ end of each variable value.
need create short script reads values of my_var1 , my_var2.
need end 2 variables follows:

my_var1 = value of first var my_var2 = subvar1=27, subvar2=hello1 

i have basic installation of centos 7, , can't install additional stuff in machine.
how can achieve it?

i assume variable names beginning of lines, = sign (excluded) leading , trailing blanks removed (you cannot have blanks in variable names).

if want print output show, can use like:

while read line;     if [[ $line =~ ^[[:blank:]]*([^[:blank:]]+)[[:blank:]]*=(.*)$ ]];         var="${bash_rematch[1]}"         val="${bash_rematch[2]}"         echo "$var = $val"      fi done < <( my_command ) 

the =~ operator pattern matching regular expressions. regular expression ^[[:blank:]]*([^[:blank:]]+)[[:blank:]]*=(.*)$ models output line of command variable assignment. matches if variable name surrounded blanks. 2 sub-expressions (enclosed in ()) isolated: variable name , value. bash_rematch array contains patterns matched sub-expressions in cells 1 , 2, respectively.

if want assign variables:

while read line;     if [[ $line =~ ^[[:blank:]]*([^[:blank:]]+)[[:blank:]]*=(.*)$ ]];         var="${bash_rematch[1]}"         val="${bash_rematch[2]}"         echo "$var = $val"         declare $var="$val"      fi done < <( my_command ) 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -