Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
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

3 Answers 3

up vote 3 down vote accepted

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
share|improve this answer

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}=[^&]*"
}
share|improve this answer

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"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.