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

Martin Weitzel martin at mwtech.UUCP
Thu Jan 31 00:18:20 AEST 1991


In article <2586 at root44.co.uk> gwc at root.co.uk (Geoff Clare) writes:
>In <1064 at mwtech.UUCP> martin at mwtech.UUCP (I) writes:
>
>>	sed 's/foobar/'"$string"'/g'
>
>>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.
>
>Yes there is.  Simply create a copy of $string with '/' changed to '\/'.
                ^^^^^^
>While you're at it, you can treat '&' and '\' the same way to prevent
>sed from interpreting '&', '\1', etc. if they happen to occur in $string.
>
>Xstring=`sed 's/[\/&\\]/\\&/g' <<!
>$string
>!
>`
>sed 's/foobar/'"$Xstring"'/g'

Obviously our view of "simple" differs :-). IMHO no need to argue further.

Geoff's proposual to also protect embedded backslashes is important for
another reason: What would happen if "$string" contains the two characters
backslash and slash in sequence and you would only change the "/" to "\/" ?

One loophole still remains even in Geoff's solution: embedded newlines in
$string. It might not be important in many cases, but if the contents of
"$strings" comes from any kind of user input (procedure arg, interactive
read), the user may be able to create trouble. Again that might be not
important, but trying to break some program in an unforseen way might be
the first step for an intruder to create a security breach - one of the
best practical examples for this was the "Internet Worm".
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.shell mailing list