Regular expression with SED

Hi!

I'm trying to write a regexp but I have no luck...

I have a string like this:

param1=sometext&param2=hello&param3=bye

Also, the string can be simply:

param2=hello

I want to return the value of param2: "hello".

How can I do this?

Thanks.

You need backreferences here, which need the -r switch.

sed -r 's/^.*param2=([^&]*).*$/\1/g'

Thanks. I'm new to regexp and there are 2 things that I don't understand.

([^&]*)

This matches 0 or more characters that are not &, right? This will match the string "hello" in the first situation (ended by &).

.*$

I now that the $ symbol matches the end of line, but I don't understand why do you put .*

Can you explain me how do you match the string "hello"?

What does the last "g"?

Correct, it matches 0 or more charcters of that. The brackets surrounding it have a special meaning when you run sed with -r: it remembers that specific section in order to refer to it later. We match the entire string and keep the bit we want with brackets.

The .*$ lets the pattern match the entire string so it can replace the entire string. We want to delete everything after the hello, so we have to match it too.

Having matched the whole string, we keep the part we want as a backreference. \1 refers to the first section in brackets, \2 the second, and so forth. It needs the -r flag to work.

The last 'g' lets it match the pattern more than once if possible. Observe:

$ echo ababab | sed 's/a/b/'
bbabab
$ echo ababab | sed 's/a/b/g'
bbbbbb
$