not being able to escape "$" is doing my head in.

why oh why oh why is this happening?

i need to replace the $ with \$ in the file below

file=products_jsp\$products_jspHelper.class

echo $file

products_jsp$products_jspHelper.class


this works

echo ${file} | sed 's/\$/\\$/'

products_jsp\$products_jspHelper.class


but this doesn't

file=`echo ${file} | sed 's/\$/\\$/'`

echo $file

products_jsp$products_jspHelper.class$

i need the new $file variable to be the old $file variable but with the $ escaped.

why is it seeing $ as the 'end of line' special character? it should be escaped.

thanks in advance.

As usual, your problem is with quoting.

file='products_jsp$products_jspHelper.class'  # single quotes don't need backslashes
file="`echo "$file" | sed 's/\\$/\\\\$/'`"
echo "$file"

When you echo $file without double quotes, the shell will do backslash parsing etc. The simple lesson to learn is to always use double quotes around variables.

The doubling of backslashes in the sed expression is also an artefact of the shell's backslash parsing. In order to get a literal backslash in the regular expression, sed wants it doubled; but each of those doubled backslashes needs to be backslash-escaped in order for the shell to pass it literally to sed. (Whew.)

(Oh, and lesson two: don't trust echo to tell you the truth, the whole truth, and nothing but the truth.)

thanks, that works now.

i've just wasted about 2 hours trying a billion combinations through being stubborn and refusing to ask for help. i can now move on and finish my work.

cheers very much.