0

I have a variable b:

name=John&login=John99

John and John99 are not a constant. I would like to put substring of b in another varriable so when I type this statement in bash:

  • echo $variable it will print John
  • echo $variable2 it will print John99

I would be grateful for help.

Dago
  • 788
  • 2
  • 9
  • 24
  • 1
    Do you want to do http query decoding? In that case using a library is more appropriate since the encoding uses *percentage-encoding* as well. – Willem Van Onsem Jan 04 '16 at 22:58

1 Answers1

2

Assuming that you only care about plain ASCII characters and not entity encoding:

variable=${b#*name=}          # trim everything up to and including "name=" in b
variable=${variable%%"&"*}    # trim everything following first "&" in variable

variable2=${b#*login=}        # trim everything up to and including "login=" in b
variable2=${variable2$$"&"*}  # trim everything following first "&" in variable2

Alternately, if you really want to use regular expressions, you can do so as follows:

re_name='name=([^$]+)([&]|$)'
[[ $b =~ $re_name ]] && variable=${BASH_REMATCH[1]}
re_login='login=([^$]+)([&]|$)'
[[ $b =~ $re_login ]] && variable2=${BASH_REMATCH[1]}

References:

Also, if you do want to do HTML entity decoding, see Bash script to convert from HTML entities to characters

Community
  • 1
  • 1
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441