Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!samsung!uakari.primate.wisc.edu!ames!sun-barr!newstop!sun!amdahl!krs From: krs@uts.amdahl.com (Kris Stephens [Hail Eris!]) Newsgroups: comp.unix.shell Subject: Re: sed 's/foobar/$string/g'.... can't do this? Keywords: sed Message-ID: <7ejp01gY0c.900@amdahl.uts.amdahl.com> Date: 21 Jan 91 22:09:46 GMT References: <1991Jan17.003856.469@unicorn.cc.wwu.edu> <135@edi386.UUCP> <1991Jan21.124531.27867@siesoft.co.uk> Reply-To: krs@amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) Distribution: comp Organization: Amdahl Corporation, Sunnyvale CA Lines: 51 >>In article <1991Jan17.003856.469@unicorn.cc.wwu.edu> n8743196@unicorn.cc.wwu.edu (Jeff Wandling) writes: >>- >>-I tried: >>- >>-set string = newfoobar >>-cat file | sed 's/foobar/$string/g' .... >>- > >>You might try this : > >> string=newfoobar >> cat file | sed 's/foobar/'$string'/g' ... > I usually do it like: string=newfoobar sed "s/foobar/$string/g" file which saves a fork/exec and pipe for cat. If you really don't want to specify the file as an arg to sed, sed "s/foobar/$string/g" < file If the matched string (foobar in the example) needs to include a shell- special character, obviously you'd need to escape it. For instance, if foobar is double-quote delimited and so must the replacement text be: string='"newfoobar"' sed "s/\"foobar\"/$string/g" < file The quotes around the definition of string keep the double-quotes from being evaluated, and the double-quotes around the sed command keep them from be evaluated there, too. I think these are easier to read than the composite string sed 's/foobar/'$string'/g' and safer, too, because the 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. ...Kris -- Kristopher Stephens, | (408-746-6047) | krs@uts.amdahl.com | KC6DFS Amdahl Corporation | | | [The opinions expressed above are mine, solely, and do not ] [necessarily reflect the opinions or policies of Amdahl Corp. ]