Re: sed problem: variables countaining special symbols




Chris F.A. Johnson wrote:
On 2006-08-21, Andy B wrote:

Chris F.A. Johnson wrote:
On 2006-08-21, Andy B wrote:
Hi Guys,

Wonder if you can help, this problem is getting me down.

My script is falling over with a sed problem.

NEWSTORE=JvHCdEMzDegPI
NPASS=EoWH/Q4hds7nA

sed -e '/bill/s/'"${NEWSTORE}"'/'"${NPASS}"'/g' /tmp/temp

The above sed command works fine when there are no "special characters"
but when they appear as above i get a sed: command garbled: error.
Tried a few things with no luck, to escape theses.

That's bacause $NPASS contains a slash. Use a different delimiter
with sed:

sed -e "/bill/s|${NEWSTORE}|${NPASS}|g" /tmp/temp

I would love to do this only problem is that the 2 variables

$NEWSTORE and $NPASS, will be generated from a file that may have
special characters in it ie !"£$%^&* etc, so what i need sed to do is
read the variable in and ignore any special character that are in that
variable.

Is there a way round this at all?

You can escape the slashes within the variables, e.g.:

NEWSTORE=$( printf "%s\n" "$NEWSTORE" | sed 's|/|\\/|g' )


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence

Not for me to comment on a CFAJ post, but being a lazy admin, I would
chnage the fun chars to some thing safe and simle, tilde, dash, etc. I
used tr, worked on bash, linux. The tr needs to understand the set "[
]". My older AIX was not that smart.
printf "\n%s\n" '!"£$%^&*'|tr '[!"£$%^&*]' "~"
2 cents JB

.



Relevant Pages