Using SED in a script

Saint Aardvark the Carpeted aardvark at saintaardvarkthecarpeted.com
Tue Feb 17 21:21:38 PST 2004


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
-- 
Saint Aardvark the Carpeted
aardvark at saintaardvarkthecarpeted.com
Because the plural of Anecdote is Myth.


More information about the freebsd-questions mailing list