ed problem

Root Boy Jim rbj at dsys.ncsl.nist.gov
Sat Sep 2 01:34:56 AEST 1989


? From: Paul English x3168 <pme at io.uucp>

? dinah at krebs.bcm.tmc.edu writes:

? >I am having problem with the following script. I want to edit some
? >c files that begin with AA_. I and to change all combinations of AA_
? >to the corresponding BB_. [...]

? It is not necessary to use grep first to filter out files which
? contain the pattern, and in fact it makes extra work. Let ed look for
? the pattern. If it doesn't find it, that is ok.

Good point. No point in scanning text twice.

? I would recommend something like the following, a general purpose
? ``edit files and globally replace pattern'' shell script. (I call this
? script `edg'.)

?     :
?
?     if [ $# -lt 3 ]; then
? 	echo "usage: $0 OLDSTR NEWSTR FILES"
? 	exit 1
?     fi
?
?     old=$1; new=$2; shift 2
?
?     for file
?     do
? 	echo $file
? 	ed - $file << +
? 	    1,\$s'$old'$new'g
? 	    w
?     +
?     done

? Thus, you would invoke it like this:
?     % edg AA_ BB_ *.c
? When it edits a file without AA_, ed will complain with a `?', but you
? can ignore it.    

Except that you don't want to use ed, you want to use sed. Replace the
guts between `do' and `done' with the following

	echo $file
	sed "s'$1'$2'g" $file > $$
	mv $$ $file

There are several problems with this. First, if the pattern contains
single quotes, it will fail. Second, if it contains regular expression
characters, they must be quoted by the appropraite number of
backslashes, an interesting exercise. Third, I use $$, the pid name of
the shell as a temp file. If it previously existed, it willl be wiped
out. Since this is not my problem, I decline to solve it further.

? Paul M. English
?   Interleaf, Cambridge: pme at ileaf.com, !{sun!sunne,mit-eddie}!ileaf!pme
?   UMass/Boston: pme at umb.edu, !harvard!umb!pme

	Root Boy Jim and
	the GNU Bohemians



More information about the Comp.unix.questions mailing list