sed 's/foobar/$string/g'.... can't do this?

Martin Weitzel martin at mwtech.UUCP
Wed Jan 23 12:59:02 AEST 1991


In article <7ejp01gY0c.900 at amdahl.uts.amdahl.com> krs at amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) writes:
...
>	sed 's/foobar/'$string'/g'
>
>... value stored in string won't be evaluated
>by the shell if it contains metacharacters.  For example, if string was
>set to 'newfoobar?*' (without the contained double-quotes) and the files
>newfoobar12 and newfoobar13 existed, sed would replace 'foobar' with
>'newfoobar12 newfoobar13' if called 's/foobar/'$string'/g' , making its
>editing PWD-dependent.

For exactly that reason I've fallen into the habbit (and it normally
doesn't hurt) to double-quote every variable used in a shell script.
I'd prefer to write the above as follows:

	sed 's/foobar/'"$string"'/g'

There are few occasions where yo want file name expansion and/or IFS-
interpretation for the contents of some variable. If you are not sure
about the contents (maybe it is read as input or is a user-supplied
argument) double-quoting any usage seems strongly advisable.

BTW: There's no simple way to stop sed from complaining when the variable
`string' contains a slash, except if you know that it does contain a slash
and use some other seperator in the s-commando.
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.shell mailing list