SED

sed is the unix `stream editor'. Its functionality follows its name: sed operates on an input file line by line, and edits each line according to the instructions you give it. sed is a great way to edit lots of files simultaneously. It is available with every unix system I've seen. A similar unix command that may or may not be better suited to your applications is awk. The format I usually use for sed is

where `a.sed' is a file that has sed commands in them. Or if you'd rather you can run sed in command mode:

sed commands tend to look like those in vi. Here are some examples:
   COMMAND				FUNCTIONALITY
s/string1/string2/              substitutes string2 for the first occurence of
				string1 in each line

s/string1/string2/g             substitutes string2 for string1 everywhere
				in each line

2 s/limits.*/hello/		in line 2, looks for the string 'limits.*'
				where * is any string, and replaces with 'hello'

2,4 s/junk/try/			substitutes 'try' for the first occurence of 'junk'
				in lines 2 through 4 only

8 a\				appends the string 'set c=818.'
set c=818.			after line 8

8 a\				appends the string 'set i1=(i+c)/c - 1'
set i1=(i+c)\/c - 1		after line 8. Note the use of the \ is needed to print out
				`special characters', like /, &, %, $, and of course, \ itself

8 i\				inserts the string 'set c=818.'
set c=818.			before line 8


Suppose you have 50 files, and they all need to have 'junk' replaced by 'try' in lines 2 through 10. You could edit all 50 files individually (what a pain), or do it quickly with sed. If the files are named file1, file2, etc. you could do the following:

vi a.sed, and create a file that looks like:

2,10 s/junk/try/

Back at the unix prompt type:
ls file*

You get:
file1
file10
file11
...
file50

Now type:
ls file* | sed 's/.*/cat & | sed -f a.sed > tmp; mv -f tmp &/' > doit

which is of the form:
inputlines | sed 'sed-command' > outputfile

sed stores each line (the .* in the above command) in a variable called & (it does this
by default), and substitutes 

cat & | sed -f a.sed > tmp; mv -f tmp &

for the line. 

So the file 'doit' looks like:
cat file1 | sed -f a.sed > tmp; mv -f tmp file1
cat file10 | sed -f a.sed > tmp; mv -f tmp file10
cat file11 | sed -f a.sed > tmp; mv -f tmp file11
...
cat file50 | sed -f a.sed > tmp; mv -f tmp file50

Execute these commands by typing: 
cat doit | csh

You can do all of this in one line by typing:
ls file* | sed 's/.*/cat & | sed -f a.sed > tmp; mv -f tmp &/' | csh

Another way to accomplish this renaming (courtesy J. Salk) is:
for f in file*; do mv $f tmp; sed '2,10 s/junk/try/g' tmp >$f; done

View this page in German
Back to Hartigan's Home Page
Patrick Hartigan
hartigan@sparky.rice.edu