Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 18 Feb 2004 08:15:44 -0600 (CST)
From:      "Jack L. Stone" <webster@sageweb.net>
To:        Saint Aardvark the Carpeted <aardvark@saintaardvarkthecarpeted.com>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Using SED in a script
Message-ID:  <20040218081341.X55342@sageweb.net>
In-Reply-To: <20040218051629.GJ2197@hardesty.saintaardvarkthecarpeted.com>
References:  <20040217183030.N52674@sageweb.net> <20040218051629.GJ2197@hardesty.saintaardvarkthecarpeted.com>

next in thread | previous in thread | raw e-mail | index | archive | help

On Tue, 17 Feb 2004, Saint Aardvark the Carpeted wrote:

> Jack L. Stone disturbed my sleep to write:
> > This would be the steps:
> > - grep(1) the new string and pipe to sed(1) ..??
> > - sed(1) to find the old string & replace with the new string in a file.
> > Am I on the right track....??
>
> I think so, yeah -- something like this should work:
>
> 	#!/bin/sh
>
> 	new=`grep foo /path/to/bar`
> 	old=`cat /path/to/oldvariable`
>
> 	sed -i.bak -e "s/$old/$new/" /file/to/edit
>
> Note that I'm using double quotes (") rather than the single quotes (')
> you usually see with sed scripts; that's so I can use $newvariable
> and still have the varible substituted in.  This assumes there's nothing
> in $old or $new that would need to be escaped (quotes, slashes, etc).
> Also, my simplistic example for grep and cat assumes that the product of
> each is the thing you need to search/replace and nothing else -- if you
> need the third field (say), look at awk(1).  The "-i" option tells sed
> to edit the file in place, but keep a backup named "/file/to/edit.bak".
>
> Another, and maybe more robust approach, to editing the file would be to
> try Perl, Programming Language of the Elder Gods.  (Yeah, I'm a fan. :-).
> The last line could be replaced by:
>
> 	perl -i.bak -new="$new" -old="$old" -e's/$old/$new/' \
> 		/file/to/edit
>
> ...which would be a way of getting difficult values of new and old into
> single quotes.
>
> HTH,
> Hugh


Hugh: Thanks for the reply. This gives me two interesting approaches which
should do the job.

Appreciate it.....



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20040218081341.X55342>