3

I have this code that does work:

get_parameter ()
{
   echo "$query" | sed -n 's/^.*name=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
}

But I want to replace the "name" with the parameter that I pass to get_parameter

get_parameter ()
{
   echo "$query" | sed -n 's/^.*$1=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
}
NAME=$( get_parameter name )

This however, doesn't work. Where am I wrong?

michelemarcon
  • 3,357
  • 10
  • 32
  • 37
  • As an aside, it only needs a single sed call... `sed -rn "/^.*$1=([^&]*).*$/{ s//\1/; s/%20/_/g; p }"` ...(I used an underscore to stop it line wrapping) – Peter.O Sep 21 '11 at 11:35
  • Does this answer your question? [How can I use variables in the LHS and RHS of a sed substitution?](https://unix.stackexchange.com/questions/69112/how-can-i-use-variables-in-the-lhs-and-rhs-of-a-sed-substitution) – Kusalananda Dec 25 '21 at 21:03

4 Answers4

5

As l0b0 pointed, you can't use single quotes here. Apart from that, in your example you don't have to use sed either. It looks far cleaner with grep:

get_parameter ()
{
   echo "$query" | grep -o "${1}=[^&]*" | sed "s/%20/ /g"
}

Without echo:

get_parameter ()
{
   <<< "$query" grep -o "${1}=[^&]*" | sed "s/%20/ /g"
}

And finally, without the second sed (just bash):

get_parameter ()
{
   <<< "${query//%20/ }" grep -o "${1}=[^&]*"
}
rozcietrzewiacz
  • 38,754
  • 9
  • 94
  • 102
4

Quoting: In short, variables are not replaced with their values inside 'single-quoted' strings (aka. "variable substitution"). You need to use any one of "double quotes", $'dollar quotes', or

<<EOF
here strings
EOF
l0b0
  • 50,672
  • 41
  • 197
  • 360
0

change:

echo "$query" | sed -n 's/^.*$1=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"

to:

echo "$query" | sed -n 's/^.*'"$1"'=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
Michał Šrajer
  • 2,808
  • 17
  • 17
0

You can concating it with rest command by replace name with '$1' like the following:

sed -n 's/^.*'$1'=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
  • Note that you are leaving `$1` unquoted in the shell. – Kusalananda Dec 25 '21 at 21:04
  • @they I know and that is the right way to write it!! Also, I am already using it with the same syntax, so you might misunderstand it!! – Abdelazeem Kuratem Dec 25 '21 at 21:17
  • To quote the expansion of `$1` in your command, use `sed -n 's/^.*'"$1"'=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"`. Test your command with `$1` set to the string `1 2 3`. Then also test with `*` and `/` and add a caveat to you answer about how `$1` would be interpreted as a regular expression, and that it can't contain the delimiter used with the substitution command, and what to do instead. – Kusalananda Dec 25 '21 at 21:37